From fb58e1db34e2b97e20ef570d8e566247da129577 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 24 Aug 2026 08:34:11 +0100 Subject: [PATCH] refactor: migrate repository documentation from Markdown to AsciiDoc --- ARCHITECTURE.adoc | 48 + ARCHITECTURE.md | 47 - CHANGELOG.adoc | 74 ++ CHANGELOG.md | 72 -- CODE_OF_CONDUCT.adoc | 60 ++ CODE_OF_CONDUCT.md | 41 - COMPATIBILITY.adoc | 236 +++++ COMPATIBILITY.md | 219 ----- CONTRIBUTING.adoc | 99 ++ CONTRIBUTING.md | 89 -- GOVERNANCE.adoc | 60 ++ GOVERNANCE.md | 60 -- HANDOVER_SANCTIFY.adoc | 872 ++++++++++++++++ HANDOVER_SANCTIFY.md | 755 -------------- PHP_AEGIS_ANALYSIS_SUMMARY.adoc | 456 +++++++++ PHP_AEGIS_ANALYSIS_SUMMARY.md | 413 -------- ...PLAN.md => PHP_AEGIS_DEVELOPMENT_PLAN.adoc | 551 ++++++----- POSITIONING.adoc | 294 ++++++ POSITIONING.md | 231 ----- PROOF-NEEDS.adoc | 39 + PROOF-NEEDS.md | 25 - ROADMAP_PRIORITY.adoc | 386 ++++++++ ROADMAP_PRIORITY.md | 327 ------ SECURE_DEFAULTS.adoc | 927 ++++++++++++++++++ SECURE_DEFAULTS.md | 811 --------------- SECURITY.adoc | 52 + SECURITY.md | 44 - TEST-NEEDS.adoc | 95 ++ TEST-NEEDS.md | 61 -- TOPOLOGY.md => TOPOLOGY.adoc | 39 +- ...RATION.md => CERRO-TORRE-INTEGRATION.adoc} | 352 ++++--- docs/VALIDATION-PLAN.adoc | 400 ++++++++ docs/VALIDATION-PLAN.md | 421 -------- docs/tech-debt-2026-05-26.adoc | 71 ++ docs/tech-debt-2026-05-26.md | 57 -- llm-warmup-dev.adoc | 19 + llm-warmup-dev.md | 16 - llm-warmup-user.adoc | 19 + llm-warmup-user.md | 16 - validation/FINDINGS-AND-RECOMMENDATIONS.adoc | 645 ++++++++++++ validation/FINDINGS-AND-RECOMMENDATIONS.md | 536 ---------- validation/README.adoc | 276 ++++++ validation/README.md | 261 ----- validation/VALIDATION-REPORT.adoc | 424 ++++++++ validation/VALIDATION-REPORT.md | 401 -------- 45 files changed, 6055 insertions(+), 5342 deletions(-) create mode 100644 ARCHITECTURE.adoc delete mode 100644 ARCHITECTURE.md create mode 100644 CHANGELOG.adoc delete mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.adoc delete mode 100644 CODE_OF_CONDUCT.md create mode 100644 COMPATIBILITY.adoc delete mode 100644 COMPATIBILITY.md create mode 100644 CONTRIBUTING.adoc delete mode 100644 CONTRIBUTING.md create mode 100644 GOVERNANCE.adoc delete mode 100644 GOVERNANCE.md create mode 100644 HANDOVER_SANCTIFY.adoc delete mode 100644 HANDOVER_SANCTIFY.md create mode 100644 PHP_AEGIS_ANALYSIS_SUMMARY.adoc delete mode 100644 PHP_AEGIS_ANALYSIS_SUMMARY.md rename PHP_AEGIS_DEVELOPMENT_PLAN.md => PHP_AEGIS_DEVELOPMENT_PLAN.adoc (55%) create mode 100644 POSITIONING.adoc delete mode 100644 POSITIONING.md create mode 100644 PROOF-NEEDS.adoc delete mode 100644 PROOF-NEEDS.md create mode 100644 ROADMAP_PRIORITY.adoc delete mode 100644 ROADMAP_PRIORITY.md create mode 100644 SECURE_DEFAULTS.adoc delete mode 100644 SECURE_DEFAULTS.md create mode 100644 SECURITY.adoc delete mode 100644 SECURITY.md create mode 100644 TEST-NEEDS.adoc delete mode 100644 TEST-NEEDS.md rename TOPOLOGY.md => TOPOLOGY.adoc (88%) rename docs/{CERRO-TORRE-INTEGRATION.md => CERRO-TORRE-INTEGRATION.adoc} (66%) create mode 100644 docs/VALIDATION-PLAN.adoc delete mode 100644 docs/VALIDATION-PLAN.md create mode 100644 docs/tech-debt-2026-05-26.adoc delete mode 100644 docs/tech-debt-2026-05-26.md create mode 100644 llm-warmup-dev.adoc delete mode 100644 llm-warmup-dev.md create mode 100644 llm-warmup-user.adoc delete mode 100644 llm-warmup-user.md create mode 100644 validation/FINDINGS-AND-RECOMMENDATIONS.adoc delete mode 100644 validation/FINDINGS-AND-RECOMMENDATIONS.md create mode 100644 validation/README.adoc delete mode 100644 validation/README.md create mode 100644 validation/VALIDATION-REPORT.adoc delete mode 100644 validation/VALIDATION-REPORT.md diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc new file mode 100644 index 0000000..1c0a7a6 --- /dev/null +++ b/ARCHITECTURE.adoc @@ -0,0 +1,48 @@ +== Architecture + +=== Overview + +This repository follows a modular, maintainable architecture designed +for clarity, scalability, and long-term sustainability. + +=== Directory Structure + +.... +. +├── src/ # Source code +├── tests/ # Test suites +├── docs/ # Documentation +├── scripts/ # Utility scripts +├── config/ # Configuration files +├── LICENSE # License file +├── LICENSES/ # Full license texts +└── README.adoc # Project documentation +.... + +=== Design Principles + +* *Separation of Concerns*: Each module has a single responsibility +* *Testability*: Code is written to be easily testable +* *Documentation*: All public APIs are documented +* *Configuration*: Environment-specific settings are externalized + +=== Dependencies + +* External dependencies are minimized and clearly declared +* Version pinning is used for reproducibility + +=== Security Considerations + +* Sensitive data is never committed to the repository +* Secrets are managed through environment variables or secure vaults +* Regular dependency audits are performed + +=== Maintainability + +* Code follows consistent style guidelines +* Pull requests require review and CI checks +* Issues and discussions are tracked transparently + +''''' + +_Last updated: 2026-07-18_ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md deleted file mode 100644 index 607e3d8..0000000 --- a/ARCHITECTURE.md +++ /dev/null @@ -1,47 +0,0 @@ -# Architecture - -## Overview - -This repository follows a modular, maintainable architecture designed for clarity, scalability, and long-term sustainability. - -## Directory Structure - -``` -. -├── src/ # Source code -├── tests/ # Test suites -├── docs/ # Documentation -├── scripts/ # Utility scripts -├── config/ # Configuration files -├── LICENSE # License file -├── LICENSES/ # Full license texts -└── README.adoc # Project documentation -``` - -## Design Principles - -- **Separation of Concerns**: Each module has a single responsibility -- **Testability**: Code is written to be easily testable -- **Documentation**: All public APIs are documented -- **Configuration**: Environment-specific settings are externalized - -## Dependencies - -- External dependencies are minimized and clearly declared -- Version pinning is used for reproducibility - -## Security Considerations - -- Sensitive data is never committed to the repository -- Secrets are managed through environment variables or secure vaults -- Regular dependency audits are performed - -## Maintainability - -- Code follows consistent style guidelines -- Pull requests require review and CI checks -- Issues and discussions are tracked transparently - ---- - -*Last updated: 2026-07-18* diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc new file mode 100644 index 0000000..f1e75e3 --- /dev/null +++ b/CHANGELOG.adoc @@ -0,0 +1,74 @@ +== Changelog + +All notable changes to `+php-aegis+` will be documented in this file. + +This file is generated from conventional commits by the +https://github.com/hyperpolymath/standards/blob/main/.github/workflows/changelog-reusable.yml[`+changelog-reusable.yml+`] +workflow (`+hyperpolymath/standards#206+`). Adopt the workflow in this +repo’s CI to keep this file in sync automatically — see +https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml[`+templates/cliff.toml+`] +for the canonical config. + +The format follows https://keepachangelog.com/en/1.1.0/[Keep a +Changelog]; this project aims to follow +https://semver.org/spec/v2.0.0.html[Semantic Versioning]. + +=== [Unreleased] + +==== Added + +* feat(crg): add crg-grade and crg-badge justfile recipes +* feat: add VeriSimDbStore rate limit storage backend +* feat: add stapeln.toml container definition +* feat: deploy UX Manifesto infrastructure +* feat: add CLADE.a2ml — clade taxonomy declaration +* feat: adopt contractile system +* feat: add AI Gatekeeper Protocol manifest +* feat(ci): enable Hypatia scanning +* feat: add Cerro Torre verified container integration +* feat: add post-quantum cryptographic primitives module + +==== Fixed + +* fix(ci): bump a2ml/k9-validate-action pins to canonical (#27) +* fix(ci): sync hypatia-scan.yml to canonical (#26) +* fix(ci): build Hypatia escript from repo root (estate dogfood drift) +* fix(scorecard): enforce granular permissions and add fuzzing +placeholder +* fix(ci): Resolve workflow-linter self-matching and metadata issues +* fix: global AGPL-3.0-or-later → PMPL-1.0-or-later replacement +* fix: SPDX headers (AGPL→PMPL), email, author name +* fix(license): SPDX AGPL-3.0 → PMPL-1.0-or-later in dotfiles +* fix: update STATE.scm to actual 90% status, fix SPDX and license +metadata +* fix: remove duplicate SCM files from root + +==== Changed + +* refactor: migrate 6SCM → 6A2 (.scm → .a2ml format) + +==== Documentation + +* docs: substantive CRG C annotation (EXPLAINME.adoc) +* docs: add TEST-NEEDS.md and/or PROOF-NEEDS.md from audit +* docs: add EXPLAINME.adoc — prove-it file backing README claims +* docs: add checkpoint files for state tracking + +==== CI + +* ci: redistribute concurrency-cancel guard to read-only check workflows +(#29) +* ci: bump actions/upload-artifact SHA to current v4 (#24) +* ci: SHA-pin hyperpolymath validate-actions in dogfood-gate +* ci: restore Dependabot security path + wire auto-merge +* ci: deploy dogfood-gate, add Groove manifest, K9 contracts, CRG tests + +=== Pre-history + +Prior commits to this file’s introduction are recorded in git history +but not formally classified into Keep-a-Changelog sections. To backfill, +run `+git cliff -o CHANGELOG.md+` locally using the canonical +https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml[`+cliff.toml+`] +— this is one-shot mechanical work. + +''''' diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 3fbbb5a..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,72 +0,0 @@ - - -# Changelog - -All notable changes to `php-aegis` will be documented in this file. - -This file is generated from conventional commits by the -[`changelog-reusable.yml`](https://github.com/hyperpolymath/standards/blob/main/.github/workflows/changelog-reusable.yml) -workflow (`hyperpolymath/standards#206`). Adopt the workflow in this repo's CI to keep this file in sync automatically — see -[`templates/cliff.toml`](https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml) -for the canonical config. - -The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); -this project aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added - -- feat(crg): add crg-grade and crg-badge justfile recipes -- feat: add VeriSimDbStore rate limit storage backend -- feat: add stapeln.toml container definition -- feat: deploy UX Manifesto infrastructure -- feat: add CLADE.a2ml — clade taxonomy declaration -- feat: adopt contractile system -- feat: add AI Gatekeeper Protocol manifest -- feat(ci): enable Hypatia scanning -- feat: add Cerro Torre verified container integration -- feat: add post-quantum cryptographic primitives module - -### Fixed - -- fix(ci): bump a2ml/k9-validate-action pins to canonical (#27) -- fix(ci): sync hypatia-scan.yml to canonical (#26) -- fix(ci): build Hypatia escript from repo root (estate dogfood drift) -- fix(scorecard): enforce granular permissions and add fuzzing placeholder -- fix(ci): Resolve workflow-linter self-matching and metadata issues -- fix: global AGPL-3.0-or-later → PMPL-1.0-or-later replacement -- fix: SPDX headers (AGPL→PMPL), email, author name -- fix(license): SPDX AGPL-3.0 → PMPL-1.0-or-later in dotfiles -- fix: update STATE.scm to actual 90% status, fix SPDX and license metadata -- fix: remove duplicate SCM files from root - -### Changed - -- refactor: migrate 6SCM → 6A2 (.scm → .a2ml format) - -### Documentation - -- docs: substantive CRG C annotation (EXPLAINME.adoc) -- docs: add TEST-NEEDS.md and/or PROOF-NEEDS.md from audit -- docs: add EXPLAINME.adoc — prove-it file backing README claims -- docs: add checkpoint files for state tracking - -### CI - -- ci: redistribute concurrency-cancel guard to read-only check workflows (#29) -- ci: bump actions/upload-artifact SHA to current v4 (#24) -- ci: SHA-pin hyperpolymath validate-actions in dogfood-gate -- ci: restore Dependabot security path + wire auto-merge -- ci: deploy dogfood-gate, add Groove manifest, K9 contracts, CRG tests - -## Pre-history - -Prior commits to this file's introduction are recorded in git history but not formally classified into Keep-a-Changelog sections. To backfill, run `git cliff -o CHANGELOG.md` locally using the canonical [`cliff.toml`](https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml) — this is one-shot mechanical work. - ---- - - diff --git a/CODE_OF_CONDUCT.adoc b/CODE_OF_CONDUCT.adoc new file mode 100644 index 0000000..16e7066 --- /dev/null +++ b/CODE_OF_CONDUCT.adoc @@ -0,0 +1,60 @@ +== Contributor Covenant Code of Conduct + +=== Our Pledge + +We as members, contributors, and leaders pledge to make participation in +our community a harassment-free experience for everyone, regardless of +age, body size, visible or invisible disability, ethnicity, sex +characteristics, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +=== Our Standards + +Examples of behavior that contributes to a positive environment include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our +mistakes +* Focusing on what is best for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or +advances of any kind +* Trolling, insulting or derogatory comments, and personal or political +attacks +* Public or private harassment +* Publishing others’ private information without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting + +=== Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our +standards of acceptable behavior and will take appropriate and fair +corrective action in response to any behavior that they deem +inappropriate, threatening, offensive, or harmful. + +=== Scope + +This Code of Conduct applies within all community spaces, and also +applies when an individual is officially representing the community in +public spaces. + +=== Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may +be reported via https://github.com/hyperpolymath/php-aegis/issues[GitHub +Issues] or by contacting the maintainer directly. + +All complaints will be reviewed and investigated promptly and fairly. + +=== Attribution + +This Code of Conduct is adapted from the +https://www.contributor-covenant.org[Contributor Covenant], version 2.1, +available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 8ca369c..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,41 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to a positive environment include: - -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes -- Focusing on what is best for the overall community - -Examples of unacceptable behavior include: - -- The use of sexualized language or imagery, and sexual attention or advances of any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information without explicit permission -- Other conduct which could reasonably be considered inappropriate in a professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported via [GitHub Issues](https://github.com/hyperpolymath/php-aegis/issues) or by contacting the maintainer directly. - -All complaints will be reviewed and investigated promptly and fairly. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html diff --git a/COMPATIBILITY.adoc b/COMPATIBILITY.adoc new file mode 100644 index 0000000..a0c6a42 --- /dev/null +++ b/COMPATIBILITY.adoc @@ -0,0 +1,236 @@ +== php-aegis Compatibility Strategy + +____ +*Note*: This document describes the planned compatibility strategy. The +`+php-aegis-compat+` package is not yet implemented. See the +link:ROADMAP_PRIORITY.md[roadmap] for status. +____ + +=== The Problem + +php-aegis requires PHP 8.1+, but WordPress officially supports PHP 7.4+. +This limits adoption in the WordPress ecosystem where many hosts still +run PHP 7.4 or 8.0. + +=== Strategy: Dual-Package Approach + +Instead of downgrading the main library, we will provide a separate +compatibility package. + +.... +hyperpolymath/php-aegis # PHP 8.1+ (main, recommended) ✅ Available +hyperpolymath/php-aegis-compat # PHP 7.4+ (polyfill, limited) 📋 Planned +.... + +==== Why Not Downgrade? + +[arabic] +. *Security*: PHP 8.1+ has better security defaults +. *Type Safety*: Union types, enums, readonly properties +. *Performance*: PHP 8.x is significantly faster +. *Maintenance*: Supporting old PHP versions increases complexity + +==== The Compatibility Package + +`+php-aegis-compat+` provides: - Same API surface as php-aegis - Works +on PHP 7.4, 8.0 - Gracefully degrades when php-aegis is available + +[source,php] +---- + [ + PhpAegis\Laravel\AegisServiceProvider::class, +], + +// Usage in controllers +public function store(Request $request, Sanitizer $sanitizer) +{ + $safe = $sanitizer->html($request->input('content')); +} + +// Blade directive +@aegis($userContent) // Calls Sanitizer::html() +---- + +''''' + +=== Migration Path + +==== For WordPress Themes/Plugins + +[source,php] +---- +// Before: Using WordPress functions only +echo esc_html($user_input); + +// After: Using php-aegis with WordPress fallback +if (function_exists('aegis_html')) { + echo aegis_html($user_input); +} else { + echo esc_html($user_input); +} + +// Or: Graceful one-liner +echo function_exists('aegis_html') ? aegis_html($user_input) : esc_html($user_input); +---- + +==== For New Projects + +[source,php] +---- +// Just use php-aegis directly +use PhpAegis\Sanitizer; + +echo Sanitizer::html($user_input); +---- + +''''' + +=== Version Support Timeline + +[cols=",,",options="header",] +|=== +|PHP Version |Support Status |Recommended Package +|7.4 |Legacy (EOL Dec 2022) |php-aegis-compat +|8.0 |Legacy (EOL Nov 2023) |php-aegis-compat +|8.1 |Security fixes only |php-aegis +|8.2 |Active |php-aegis +|8.3 |Active (current) |php-aegis +|8.4+ |Future |php-aegis +|=== + +*Recommendation*: Upgrade to PHP 8.2+ and use php-aegis directly. + +''''' + +=== Implementation Checklist + +* [ ] Create `+hyperpolymath/php-aegis-compat+` repository +* [ ] Implement core Sanitizer/Validator classes for PHP 7.4 +* [ ] Add auto-detection for php-aegis (use if available) +* [ ] Create WordPress mu-plugin adapter +* [ ] Create Laravel service provider +* [ ] Publish both packages to Packagist +* [ ] Document migration paths + +''''' + +_This strategy maximizes adoption while maintaining security and code +quality in the main package._ diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md deleted file mode 100644 index 8ce240a..0000000 --- a/COMPATIBILITY.md +++ /dev/null @@ -1,219 +0,0 @@ -# php-aegis Compatibility Strategy - -> **Note**: This document describes the planned compatibility strategy. The `php-aegis-compat` package is not yet implemented. See the [roadmap](ROADMAP_PRIORITY.md) for status. - -## The Problem - -php-aegis requires PHP 8.1+, but WordPress officially supports PHP 7.4+. This limits adoption in the WordPress ecosystem where many hosts still run PHP 7.4 or 8.0. - -## Strategy: Dual-Package Approach - -Instead of downgrading the main library, we will provide a separate compatibility package. - -``` -hyperpolymath/php-aegis # PHP 8.1+ (main, recommended) ✅ Available -hyperpolymath/php-aegis-compat # PHP 7.4+ (polyfill, limited) 📋 Planned -``` - -### Why Not Downgrade? - -1. **Security**: PHP 8.1+ has better security defaults -2. **Type Safety**: Union types, enums, readonly properties -3. **Performance**: PHP 8.x is significantly faster -4. **Maintenance**: Supporting old PHP versions increases complexity - -### The Compatibility Package - -`php-aegis-compat` provides: -- Same API surface as php-aegis -- Works on PHP 7.4, 8.0 -- Gracefully degrades when php-aegis is available - -```php - [ - PhpAegis\Laravel\AegisServiceProvider::class, -], - -// Usage in controllers -public function store(Request $request, Sanitizer $sanitizer) -{ - $safe = $sanitizer->html($request->input('content')); -} - -// Blade directive -@aegis($userContent) // Calls Sanitizer::html() -``` - ---- - -## Migration Path - -### For WordPress Themes/Plugins - -```php -// Before: Using WordPress functions only -echo esc_html($user_input); - -// After: Using php-aegis with WordPress fallback -if (function_exists('aegis_html')) { - echo aegis_html($user_input); -} else { - echo esc_html($user_input); -} - -// Or: Graceful one-liner -echo function_exists('aegis_html') ? aegis_html($user_input) : esc_html($user_input); -``` - -### For New Projects - -```php -// Just use php-aegis directly -use PhpAegis\Sanitizer; - -echo Sanitizer::html($user_input); -``` - ---- - -## Version Support Timeline - -| PHP Version | Support Status | Recommended Package | -|-------------|---------------|---------------------| -| 7.4 | Legacy (EOL Dec 2022) | php-aegis-compat | -| 8.0 | Legacy (EOL Nov 2023) | php-aegis-compat | -| 8.1 | Security fixes only | php-aegis | -| 8.2 | Active | php-aegis | -| 8.3 | Active (current) | php-aegis | -| 8.4+ | Future | php-aegis | - -**Recommendation**: Upgrade to PHP 8.2+ and use php-aegis directly. - ---- - -## Implementation Checklist - -- [ ] Create `hyperpolymath/php-aegis-compat` repository -- [ ] Implement core Sanitizer/Validator classes for PHP 7.4 -- [ ] Add auto-detection for php-aegis (use if available) -- [ ] Create WordPress mu-plugin adapter -- [ ] Create Laravel service provider -- [ ] Publish both packages to Packagist -- [ ] Document migration paths - ---- - -*This strategy maximizes adoption while maintaining security and code quality in the main package.* diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc new file mode 100644 index 0000000..39b5cf3 --- /dev/null +++ b/CONTRIBUTING.adoc @@ -0,0 +1,99 @@ +== Contributing to php-aegis + +Thank you for your interest in contributing to php-aegis! + +=== Getting Started + +==== Prerequisites + +* PHP 8.1 or higher +* Composer +* Git + +==== Development Setup + +[source,bash] +---- +# Clone the repository +git clone https://github.com/hyperpolymath/php-aegis.git +cd php-aegis + +# Install dependencies +composer install + +# Run tests to verify setup +vendor/bin/phpunit +---- + +=== How to Contribute + +==== Reporting Bugs + +[arabic] +. Check https://github.com/hyperpolymath/php-aegis/issues[existing +issues] to avoid duplicates +. Create a new issue with: +* Clear, descriptive title +* Steps to reproduce +* Expected vs actual behavior +* PHP version and environment details + +==== Suggesting Features + +[arabic] +. Open a https://github.com/hyperpolymath/php-aegis/issues/new[new +issue] with the `+enhancement+` label +. Describe the use case and security benefit +. Include example API if proposing new methods + +==== Submitting Code + +[arabic] +. Fork the repository +. Create a feature branch: `+git checkout -b feature/your-feature+` +. Write tests for new functionality +. Ensure all tests pass: `+vendor/bin/phpunit+` +. Run static analysis: `+vendor/bin/phpstan analyse src+` +. Submit a pull request + +=== Code Standards + +==== PHP Standards + +This project follows https://www.php-fig.org/psr/psr-12/[PSR-12] coding +standards. + +[source,bash] +---- +# Check formatting +vendor/bin/php-cs-fixer fix --dry-run + +# Auto-fix formatting +vendor/bin/php-cs-fixer fix +---- + +==== Documentation + +* All public methods must have PHPDoc comments +* Include `+@param+` and `+@return+` annotations +* Document security considerations where relevant + +==== Testing + +* New features require tests +* Security-related code requires comprehensive test coverage +* Use meaningful test method names: +`+test_validator_rejects_invalid_email()+` + +=== Security Contributions + +Given the security-focused nature of this project: + +* *Do not* submit PRs that fix security vulnerabilities publicly +* Instead, follow the process in SECURITY.md +* Security enhancements (new features) can be submitted normally + +=== License + +By contributing, you agree that your contributions will be licensed +under the MIT License. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 5cf7dff..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,89 +0,0 @@ -# Contributing to php-aegis - -Thank you for your interest in contributing to php-aegis! - -## Getting Started - -### Prerequisites - -- PHP 8.1 or higher -- Composer -- Git - -### Development Setup - -```bash -# Clone the repository -git clone https://github.com/hyperpolymath/php-aegis.git -cd php-aegis - -# Install dependencies -composer install - -# Run tests to verify setup -vendor/bin/phpunit -``` - -## How to Contribute - -### Reporting Bugs - -1. Check [existing issues](https://github.com/hyperpolymath/php-aegis/issues) to avoid duplicates -2. Create a new issue with: - - Clear, descriptive title - - Steps to reproduce - - Expected vs actual behavior - - PHP version and environment details - -### Suggesting Features - -1. Open a [new issue](https://github.com/hyperpolymath/php-aegis/issues/new) with the `enhancement` label -2. Describe the use case and security benefit -3. Include example API if proposing new methods - -### Submitting Code - -1. Fork the repository -2. Create a feature branch: `git checkout -b feature/your-feature` -3. Write tests for new functionality -4. Ensure all tests pass: `vendor/bin/phpunit` -5. Run static analysis: `vendor/bin/phpstan analyse src` -6. Submit a pull request - -## Code Standards - -### PHP Standards - -This project follows [PSR-12](https://www.php-fig.org/psr/psr-12/) coding standards. - -```bash -# Check formatting -vendor/bin/php-cs-fixer fix --dry-run - -# Auto-fix formatting -vendor/bin/php-cs-fixer fix -``` - -### Documentation - -- All public methods must have PHPDoc comments -- Include `@param` and `@return` annotations -- Document security considerations where relevant - -### Testing - -- New features require tests -- Security-related code requires comprehensive test coverage -- Use meaningful test method names: `test_validator_rejects_invalid_email()` - -## Security Contributions - -Given the security-focused nature of this project: - -- **Do not** submit PRs that fix security vulnerabilities publicly -- Instead, follow the process in [SECURITY.md](SECURITY.md) -- Security enhancements (new features) can be submitted normally - -## License - -By contributing, you agree that your contributions will be licensed under the MIT License. diff --git a/GOVERNANCE.adoc b/GOVERNANCE.adoc new file mode 100644 index 0000000..9b836fb --- /dev/null +++ b/GOVERNANCE.adoc @@ -0,0 +1,60 @@ +== Governance + +=== Overview + +This project is governed by the following principles and structures to +ensure transparent, inclusive, and effective decision-making. + +=== Roles and Responsibilities + +==== Maintainers + +Maintainers are responsible for: - Reviewing and merging pull requests - +Managing releases and versioning - Ensuring code quality and standards - +Triaging issues and bug reports - Community engagement and support + +==== Contributors + +Contributors are expected to: - Follow the code of conduct - Submit +well-documented pull requests - Write tests for new functionality - +Maintain existing tests - Update documentation as needed + +=== Decision Making + +==== Minor Changes + +* Can be made by any maintainer +* Include bug fixes, documentation updates, dependency updates + +==== Major Changes + +* Require discussion in issues or pull requests +* Include new features, architectural changes, API changes +* Need approval from at least 2 maintainers + +==== Breaking Changes + +* Require RFC (Request for Comments) process +* Need approval from majority of maintainers +* Must include migration guide + +=== Code of Conduct + +All participants are expected to follow our Code of Conduct. Violations +can be reported to the maintainers. + +=== Communication + +* *Issues*: For bug reports and feature requests +* *Discussions*: For questions and general discussion +* *Pull Requests*: For code contributions + +=== Licensing + +All contributions are made under the terms of the repository’s LICENSE +file. By submitting a pull request, you agree to license your +contributions accordingly. + +''''' + +_Last updated: 2026-07-18_ diff --git a/GOVERNANCE.md b/GOVERNANCE.md deleted file mode 100644 index e27364c..0000000 --- a/GOVERNANCE.md +++ /dev/null @@ -1,60 +0,0 @@ -# Governance - -## Overview - -This project is governed by the following principles and structures to ensure transparent, inclusive, and effective decision-making. - -## Roles and Responsibilities - -### Maintainers - -Maintainers are responsible for: -- Reviewing and merging pull requests -- Managing releases and versioning -- Ensuring code quality and standards -- Triaging issues and bug reports -- Community engagement and support - -### Contributors - -Contributors are expected to: -- Follow the code of conduct -- Submit well-documented pull requests -- Write tests for new functionality -- Maintain existing tests -- Update documentation as needed - -## Decision Making - -### Minor Changes -- Can be made by any maintainer -- Include bug fixes, documentation updates, dependency updates - -### Major Changes -- Require discussion in issues or pull requests -- Include new features, architectural changes, API changes -- Need approval from at least 2 maintainers - -### Breaking Changes -- Require RFC (Request for Comments) process -- Need approval from majority of maintainers -- Must include migration guide - -## Code of Conduct - -All participants are expected to follow our Code of Conduct. Violations can be reported to the maintainers. - -## Communication - -- **Issues**: For bug reports and feature requests -- **Discussions**: For questions and general discussion -- **Pull Requests**: For code contributions - -## Licensing - -All contributions are made under the terms of the repository's LICENSE file. -By submitting a pull request, you agree to license your contributions accordingly. - ---- - -*Last updated: 2026-07-18* diff --git a/HANDOVER_SANCTIFY.adoc b/HANDOVER_SANCTIFY.adoc new file mode 100644 index 0000000..c6bcfd8 --- /dev/null +++ b/HANDOVER_SANCTIFY.adoc @@ -0,0 +1,872 @@ +== Handover Document: sanctify-php Integration Insights + +=== Context + +This document summarizes findings from integrating `+php-aegis+` and +`+sanctify-php+` into a WordPress semantic theme (wp-sinople-theme). It +provides actionable recommendations for the `+sanctify-php+` team based +on real-world usage patterns. + +=== Role Clarification + +[width="100%",cols="27%,26%,47%",options="header",] +|=== +|Tool |Role |When Used +|*php-aegis* |Runtime security library |During request handling +(validation, sanitization, headers) + +|*sanctify-php* |Static analysis tool |During development/CI (find +vulnerabilities before deploy) +|=== + +These are *complementary*, not competing tools: - `+sanctify-php+` finds +the bugs - `+php-aegis+` provides the fixes + +=== Issues Discovered During Integration + +==== 1. Haskell Toolchain Dependency + +*Problem*: `+sanctify-php+` requires GHC/Cabal to build, which is a +significant barrier for PHP developers. + +*Impact*: Most PHP teams don’t have Haskell expertise or toolchain +installed. + +*Recommendations*: - Provide pre-built binaries for Linux (x86_64, +aarch64), macOS (Intel, Apple Silicon), Windows - Create official Docker +image: `+ghcr.io/hyperpolymath/sanctify-php:latest+` - Consider GitHub +Actions integration that runs analysis without local install - Add +installation via common package managers (Homebrew, apt, nix) + +*Example Docker usage*: + +[source,bash] +---- +docker run --rm -v $(pwd):/workspace ghcr.io/hyperpolymath/sanctify-php analyze /workspace +---- + +==== 2. PHP 8.x Syntax Support + +*Problem*: Parser may not handle all PHP 8.x syntax (enums, union types, +named arguments, attributes, match expressions, constructor property +promotion). + +*Test cases needed*: + +[source,php] +---- +// Enums (PHP 8.1+) +enum Status: string { + case Draft = 'draft'; + case Published = 'published'; +} + +// Union types (PHP 8.0+) +function process(string|int $input): string|false { ... } + +// Attributes (PHP 8.0+) +#[Route('/api/users')] +class UserController { ... } + +// Constructor property promotion (PHP 8.0+) +class User { + public function __construct( + public readonly string $name, + private int $age = 0, + ) {} +} + +// Named arguments (PHP 8.0+) +htmlspecialchars(string: $input, flags: ENT_QUOTES); + +// Match expressions (PHP 8.0+) +$result = match($status) { + Status::Draft => 'Editing', + Status::Published => 'Live', +}; +---- + +*Recommendation*: Add PHP 8.x grammar rules and comprehensive test +suite. + +==== 3. RDF/Turtle Output Context Awareness + +*Problem*: Static analyzer doesn’t detect RDF/Turtle injection +vulnerabilities in semantic web themes. + +*Background*: Semantic WordPress themes output RDF Turtle format for +linked data. Standard XSS detection won’t catch Turtle-specific +injection vectors. + +*Vulnerable pattern* (not currently detected): + +[source,php] +---- +// DANGEROUS: addslashes() is insufficient for Turtle +$turtle = '<' . $uri . '> rdfs:label "' . addslashes($label) . '" .'; +---- + +*Attack vectors*: + +[source,turtle] +---- +# Turtle escape sequences +\n \r \t \\ \" \uXXXX \UXXXXXXXX + +# IRI injection + owl:sameAs +---- + +*Recommendation*: Add detection rules for: - `+addslashes()+` used in +RDF/Turtle context - Unescaped variables in Turtle string literals +(`+"..."+`) - Unescaped IRIs (`+<...>+`) - Missing use of proper +escaping functions + +*Suggested rule signatures*: + +.... +turtle_string_injection: Detects unescaped user input in Turtle string literals +turtle_iri_injection: Detects unescaped user input in Turtle IRIs +rdf_semantic_injection: Detects potential semantic attacks via RDF +.... + +==== 4. WordPress Integration Documentation + +*Problem*: No clear guidance for WordPress-specific vulnerability +patterns. + +*WordPress-specific patterns to detect*: + +[source,php] +---- +// DANGEROUS: Direct $_GET/$_POST usage +echo $_GET['query']; // XSS + +// DANGEROUS: Missing nonce verification +if (isset($_POST['action'])) { ... } // CSRF + +// DANGEROUS: Direct SQL interpolation +$wpdb->query("SELECT * FROM users WHERE id = " . $_GET['id']); // SQLi + +// DANGEROUS: Unescaped output +echo $user_input; // Should use esc_html(), esc_attr(), etc. + +// DANGEROUS: Privileged action without capability check +add_action('wp_ajax_delete_user', 'delete_user_handler'); +function delete_user_handler() { + // Missing: current_user_can('delete_users') + wp_delete_user($_POST['user_id']); +} +---- + +*WordPress-specific safe patterns*: + +[source,php] +---- +// Safe escaping functions +esc_html($text) +esc_attr($attr) +esc_url($url) +wp_kses($html, $allowed) +wp_kses_post($html) + +// Safe nonce verification +wp_verify_nonce($_POST['_wpnonce'], 'action_name') +check_admin_referer('action_name') + +// Safe capability checks +current_user_can('edit_posts') +---- + +*Recommendation*: Create WordPress-specific ruleset that: - Detects +missing `+esc_*+` function usage - Detects missing nonce verification in +form handlers - Detects missing capability checks in AJAX handlers - +Recognizes WordPress sanitization functions as safe sinks + +==== 5. IndieWeb/Micropub Pattern Detection + +*Problem*: No awareness of IndieWeb protocols (Micropub, IndieAuth, +Webmention). + +*Patterns to detect*: + +[source,php] +---- +// DANGEROUS: Missing IndieAuth token verification +function handle_micropub($request) { + $content = $request['content']; // Unverified! + create_post($content); +} + +// DANGEROUS: Webmention SSRF +function verify_webmention($source) { + $response = wp_remote_get($source); // Can hit internal IPs +} + +// DANGEROUS: Micropub content injection +$mf2 = Mf2\parse($html, $source); +$content = $mf2['items'][0]['properties']['content'][0]; +echo $content; // Unsanitized from external source +---- + +*Recommendation*: Add rules for common IndieWeb vulnerability patterns. + +=== Integration Architecture + +.... +┌─────────────────────────────────────────────────────────────┐ +│ Development Workflow │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Developer │───▶│ sanctify-php │───▶│ Fix Code │ │ +│ │ Writes Code │ │ (Analysis) │ │ (Guidance) │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌──────────────┐ │ +│ │ php-aegis │ │ +│ │ (Runtime) │ │ +│ └──────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────┘ +.... + +=== Recommended sanctify-php Output Format + +When `+sanctify-php+` detects a vulnerability, it should suggest the +`+php-aegis+` fix: + +.... +VULNERABILITY: XSS in output context +FILE: theme/template.php:42 +CODE: echo $user_input; + +RECOMMENDATION: + Use php-aegis Sanitizer for proper encoding: + + Before: echo $user_input; + After: echo \PhpAegis\Sanitizer::html($user_input); + + Install: composer require hyperpolymath/php-aegis +.... + +=== Priority Recommendations Summary + +[cols=",,",options="header",] +|=== +|Priority |Issue |Effort +|P0 |Pre-built binaries / Docker image |Medium +|P0 |PHP 8.x syntax support |High +|P0 |Official GitHub Action (`+sanctify-php-action+`) |Medium +|P1 |WordPress-specific rulesets |Medium +|P1 |RDF/Turtle context detection |Medium +|P1 |SARIF output for GitHub Security tab |Low +|P2 |Incremental analysis (cache, scan changed files only) |High +|P2 |IndieWeb protocol patterns |Low +|P2 |php-aegis fix suggestions in output |Low +|=== + +''''' + +=== Additional Findings (Report 2) + +==== 6. GitHub Action Required + +*Problem*: No official GitHub Action for CI integration. + +*Impact*: Teams must write custom workflow configuration or use Docker +manually. + +*Recommendation*: Create `+hyperpolymath/sanctify-php-action+` with: + +[source,yaml] +---- +# .github/workflows/security.yml +- uses: hyperpolymath/sanctify-php-action@v1 + with: + path: ./src + config: sanctify.yml + sarif-output: results.sarif +---- + +==== 7. SARIF Output for GitHub Integration + +*What Works Well*: SARIF format enables direct GitHub Security tab +integration. + +*Enhancement*: Ensure SARIF output includes: - Rule descriptions with +OWASP references - Severity levels mapped to GitHub’s +critical/high/medium/low - Fix suggestions linking to php-aegis methods + +[source,json] +---- +{ + "runs": [{ + "tool": { "driver": { "name": "sanctify-php" } }, + "results": [{ + "ruleId": "xss-output", + "level": "error", + "message": { "text": "Unescaped output" }, + "fixes": [{ + "description": { "text": "Use PhpAegis\\Sanitizer::html()" } + }] + }] + }] +} +---- + +==== 8. Incremental Analysis + +*Problem*: Full codebase scans are slow on large projects. + +*Recommendation*: - Cache AST and taint analysis results - On subsequent +runs, only analyze changed files - Invalidate cache when dependencies +change - Use file modification timestamps or git diff + +[source,bash] +---- +# First run: full analysis, build cache +sanctify analyze ./src --cache .sanctify-cache + +# Subsequent runs: incremental +sanctify analyze ./src --cache .sanctify-cache --incremental +---- + +==== 9. Composer Plugin Wrapper + +*Problem*: PHP developers expect `+composer require+` installation. + +*Recommendation*: Create a Composer plugin that: 1. Downloads pre-built +binary for platform 2. Provides `+vendor/bin/sanctify+` wrapper 3. +Handles updates via Composer + +[source,bash] +---- +composer require --dev hyperpolymath/sanctify-php +vendor/bin/sanctify analyze ./src +---- + +''''' + +=== Standalone vs Combined Operation + +==== Minimal Requirements for Each Tool + +*php-aegis standalone* (runtime protection): - Zero dependencies (works +everywhere PHP runs) - Static methods for easy drop-in usage - Works +without sanctify-php installed + +*sanctify-php standalone* (static analysis): - Pre-built binary (no +Haskell needed) - SARIF output for any CI system - Works without +php-aegis (just reports issues) + +==== Combined Synergies + +When both tools are used together: + +.... +┌─────────────────────────────────────────────────────────────────┐ +│ Combined Workflow │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌────────────┐ ┌─────────────────┐ ┌──────────────────┐ │ +│ │ Write │──▶│ sanctify-php │──▶│ Fix with │ │ +│ │ Code │ │ (finds issues) │ │ php-aegis │ │ +│ └────────────┘ └─────────────────┘ └──────────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────┐ │ +│ │ sanctify-php recognizes php-aegis │ │ +│ │ methods as "safe sinks" in taint │ │ +│ │ analysis, reducing false positives │ │ +│ └─────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +.... + +*Key synergy*: sanctify-php should recognize php-aegis sanitizers as +safe: + +[source,haskell] +---- +-- sanctify-php taint rules +safeSinks = [ + "PhpAegis\\Sanitizer::html", + "PhpAegis\\Sanitizer::attr", + "PhpAegis\\Sanitizer::js", + "PhpAegis\\Sanitizer::css", + "PhpAegis\\Sanitizer::url", + "PhpAegis\\TurtleEscaper::string", + "PhpAegis\\TurtleEscaper::iri" +] +---- + +''''' + +=== Integration Metrics + +[cols=",,",options="header",] +|=== +|Metric |Before Integration |After Integration +|Files with `+strict_types+` |0 |24 (100%) +|PHP version |7.4+ |8.2+ +|WordPress version |5.8+ |6.4+ +|CI security checks |0 |4 +|=== + +''''' + +=== Additional Findings (Report 3: Zotpress Plugin) + +==== 10. GHC Barrier Confirmed (Critical) + +*Problem*: sanctify-php could not run on the Zotpress integration due to +missing Haskell toolchain. + +*Impact*: This is now confirmed across multiple integration attempts. +The Haskell build requirement is the #1 adoption barrier. + +*Immediate Recommendations*: 1. Provide pre-built binaries for: - Linux +x86_64 (static binary) - Linux aarch64 (for ARM servers) - macOS Intel - +macOS Apple Silicon - Windows x64 2. Publish Docker image: +`+ghcr.io/hyperpolymath/sanctify-php:latest+` 3. Create GitHub Action +that uses the Docker image internally + +*Workaround Used*: Manual analysis using sanctify-php’s documented +detection patterns. + +==== 11. WordPress Security API Overlap + +*Finding*: When analyzing mature WordPress plugins (like Zotpress), they +already follow WordPress security best practices using core functions. + +*WordPress provides equivalent security functions*: + +[width="100%",cols="30%,53%,17%",options="header",] +|=== +|php-aegis |WordPress Equivalent |Notes +|`+Validator::email()+` |`+is_email()+` |WP version is more permissive + +|`+Validator::url()+` |`+wp_http_validate_url()+` |WP has SSL +enforcement + +|`+Sanitizer::html()+` |`+esc_html()+` |Identical functionality + +|`+Sanitizer::attr()+` |`+esc_attr()+` |Identical functionality + +|`+Sanitizer::js()+` |`+esc_js()+` |WP version is context-aware + +|`+Sanitizer::url()+` |`+esc_url()+` |WP handles protocols + +|`+Sanitizer::stripTags()+` |`+wp_strip_all_tags()+` |WP handles more +edge cases +|=== + +*What sanctify-php should detect*: - Direct use of raw PHP functions +instead of WordPress equivalents - `+echo $var+` instead of +`+echo esc_html($var)+` - `+header('Location: ...')+` instead of +`+wp_redirect()+` - Missing `+exit;+` after redirect + +*sanctify-php rule suggestions*: + +[source,haskell] +---- +-- WordPress-specific rules +wpRules = [ + ("use_wp_redirect", "header\\s*\\(\\s*['\"]Location", "Use wp_redirect() instead of header()"), + ("missing_exit_redirect", "wp_redirect\\([^;]+\\);(?!\\s*exit)", "Add exit; after wp_redirect()"), + ("raw_echo", "echo\\s+\\$(?!esc_)", "Escape output with esc_html()/esc_attr()"), + ("direct_superglobal", "\\$_(GET|POST|REQUEST)\\[", "Sanitize superglobals before use") +] +---- + +==== 12. Target Audience Clarification Needed + +*Finding*: php-aegis value proposition is unclear for WordPress users. + +*Recommended positioning for sanctify-php*: + +When sanctify-php detects issues in WordPress code, suggest: 1. *First +choice*: WordPress native function (if available) 2. *Second choice*: +php-aegis function (for gaps WordPress doesn’t cover) + +.... +VULNERABILITY: Unescaped output +FILE: plugin.php:42 +CODE: echo $user_input; + +RECOMMENDATION: + WordPress: echo esc_html($user_input); + Or php-aegis: echo \PhpAegis\Sanitizer::html($user_input); +.... + +==== 13. WordPress-Unique Security Patterns + +*What sanctify-php should understand about WordPress*: + +[source,php] +---- +// WordPress-specific security patterns + +// 1. ABSPATH protection (must be at top of every PHP file) +if (!defined('ABSPATH')) exit; + +// 2. Nonce verification for forms +check_admin_referer('action_name'); +wp_verify_nonce($_POST['nonce'], 'action_name'); + +// 3. Capability checks for privileged actions +if (!current_user_can('manage_options')) return; + +// 4. Prepared statements for database +$wpdb->prepare("SELECT * FROM table WHERE id = %d", $id); + +// 5. Safe redirect +wp_safe_redirect($url); +exit; +---- + +*Detection rules needed*: - Missing ABSPATH check at file start - Form +handlers without nonce verification - AJAX handlers without capability +checks - Missing `+exit;+` after redirects + +''''' + +=== Additional Findings (Report 4: sinople-theme Full Integration) + +==== 14. Successful Integration Pattern + +*What Worked*: Full integration with WordPress theme including: - +Function wrappers: `+sinople_aegis_html()+`, `+sinople_aegis_attr()+`, +`+sinople_aegis_json()+` - Validation wrappers: +`+sinople_aegis_validate_*()+` functions - RDF/Turtle feed endpoint +using `+TurtleEscaper+` (unique value!) - Graceful fallback to WordPress +functions when php-aegis unavailable - Unit tests for the integration + +*Key Success*: TurtleEscaper proved its unique value by enabling a +`+/feed/turtle/+` endpoint. + +==== 15. sanctify-php False Positives Identified + +*Issues to address*: + +[arabic] +. *UnsafeRedirect false positive*: When `+exit;+` is on the next line + +[source,php] +---- +// This triggers false positive: +wp_redirect($url); +exit; + +// sanctify-php expects: +wp_redirect($url); exit; +---- + +[arabic, start=2] +. *MissingTextDomain false positive*: Flags WordPress core functions + +[source,php] +---- +// This may be flagged incorrectly: +__('Text', 'theme-domain'); // OK +_e('Text', 'theme-domain'); // OK +esc_html__('Text'); // May flag - but sometimes domain is optional +---- + +*Recommendation*: Add configuration options: + +[source,yaml] +---- +# sanctify.yml +rules: + UnsafeRedirect: + allow_next_line_exit: true + MissingTextDomain: + ignore_core_functions: true +---- + +==== 16. PHP 8.1+ Syntax Verification Needed + +*Concern*: Parser may not handle modern PHP syntax. + +*Test cases to verify*: + +[source,php] +---- +// Nullsafe operator (PHP 8.0+) +$value = $object?->property?->method(); + +// Match expression (PHP 8.0+) +$result = match($type) { + 'html' => Sanitizer::html($input), + 'js' => Sanitizer::js($input), + default => $input, +}; + +// Constructor property promotion (PHP 8.0+) +public function __construct( + private readonly string $name, +) {} + +// First-class callable syntax (PHP 8.1+) +$fn = Sanitizer::html(...); +---- + +==== 17. Guix Export Documentation + +*Issue*: Guix package export documentation is incomplete. + +*Recommendation*: Add to sanctify-php docs: + +[source,scheme] +---- +;; guix.scm +(use-modules (guix packages) + (guix git-download) + (guix build-system haskell)) + +(package + (name "sanctify-php") + (version "0.1.0") + (source (git-reference + (url "https://github.com/hyperpolymath/sanctify-php") + (commit (string-append "v" version)))) + (build-system haskell-build-system) + (synopsis "PHP security static analyzer") + (license license:agpl3+)) +---- + +''''' + +=== php-aegis Self-Identified Issues (Report 4) + +These issues were discovered during sinople-theme integration: + +[width="100%",cols="27%,29%,44%",options="header",] +|=== +|Issue |Status |Resolution +|`+Headers::secure()+` missing `+permissionsPolicy()+` |✅ Fixed |Added +in this PR + +|`+php-aegis-compat+` package doesn’t exist |📋 Planned |Create separate +repo + +|Not published on Packagist |📋 Planned |Publish after v0.2.0 + +|WordPress mu-plugin adapter not implemented |📋 Planned |Phase 7 +roadmap +|=== + +''''' + +=== Additional Findings (Report 5: Sinople Theme - Critical Vulnerability Fixed) + +==== 18. TurtleEscaper Fixed Real Vulnerability + +*Critical Finding*: The theme was using `+addslashes()+` for RDF Turtle +escaping - this is SQL escaping, NOT Turtle escaping. This was a real +RDF injection vulnerability. + +*Before (vulnerable)*: + +[source,php] +---- +// DANGEROUS: addslashes() is SQL escaping, not Turtle escaping! +$turtle = '"' . addslashes($label) . '"@en'; +---- + +*After (fixed)*: + +[source,php] +---- +use PhpAegis\TurtleEscaper; +$turtle = TurtleEscaper::literal($label, language: 'en'); +---- + +*This validates TurtleEscaper as the #1 unique value proposition of +php-aegis.* + +==== 19. Security Fixes Applied in Real Integration + +[width="100%",cols="34%,23%,43%",options="header",] +|=== +|Severity |Issue |Fix Applied +|CRITICAL |`+addslashes()+` for Turtle |`+TurtleEscaper::literal()+` + +|CRITICAL |IRI interpolation |`+Validator::url()+` + error handling + +|HIGH |URL validation via `+strpos()+` |`+parse_url()+` host comparison + +|HIGH |Unsanitized Micropub input |`+sanitize_text_field()+` + +`+wp_kses_post()+` + +|MEDIUM |No security headers |`+Headers::secure()+` equivalent + +|MEDIUM |No rate limiting |1-min rate limit for Webmentions + +|LOW |Missing `+strict_types+` |Added to all files +|=== + +==== 20. New Detection Rules for sanctify-php + +*RDF Turtle as Distinct Output Context*: + +sanctify-php should recognize Turtle output contexts and flag: + +[source,haskell] +---- +-- RDF Turtle detection rules +turtleRules = [ + -- Dangerous: SQL escaping in Turtle context + ("turtle_addslashes", "addslashes\\s*\\([^)]+\\).*['\"]@[a-z]{2}", + "Use TurtleEscaper::literal() instead of addslashes() for Turtle"), + + -- Dangerous: String interpolation in Turtle IRI + ("turtle_iri_interp", "<.*\\$[a-zA-Z_].*>", + "Use TurtleEscaper::iri() for Turtle IRIs"), + + -- Dangerous: Raw variable in Turtle string + ("turtle_string_raw", "\"\\$[a-zA-Z_][^\"]*\"@[a-z]", + "Use TurtleEscaper::string() for Turtle literals") +] +---- + +*WordPress REST API Pattern Recognition*: + +[source,haskell] +---- +-- WordPress REST API rules +restRules = [ + ("rest_missing_permission", "register_rest_route.*permission_callback.*__return_true", + "REST routes should verify permissions"), + + ("rest_raw_param", "\\$request\\[.*\\](?!.*sanitize)", + "Sanitize REST API parameters") +] +---- + +*WordPress Hook Detection* (reduce false positives): + +[source,haskell] +---- +-- Functions defined via add_action/add_filter are called by WordPress +wpHookFunctions = extractFunctionsFrom [ + "add_action\\s*\\([^,]+,\\s*['\"]([^'\"]+)", + "add_filter\\s*\\([^,]+,\\s*['\"]([^'\"]+)" +] +-- These should not be flagged as "unused functions" +---- + +==== 21. php-aegis Enhancement Requests + +From this integration: + +[width="100%",cols="36%,38%,26%",options="header",] +|=== +|Request |Priority |Notes +|WordPress nonce validator |Medium +|`+Validator::wpNonce($nonce, $action)+` + +|WordPress capability checker |Medium |`+Validator::wpCapability($cap)+` + +|TurtleEscaper case sensitivity docs |Low |Language tags should be +lowercase + +|SPDX identifier validator |Low |`+Validator::spdx($identifier)+` + +|Headers + WordPress integration docs |Medium |How to use with +`+wp_headers+` filter +|=== + +''''' + +=== Related Project: indieweb2-bastion + +The +https://github.com/hyperpolymath/indieweb2-bastion[indieweb2-bastion] +repository provides infrastructure-layer security that complements +php-aegis and sanctify-php at the application layer. + +==== What indieweb2-bastion Does + +[cols=",",options="header",] +|=== +|Feature |Purpose +|Hardened bastion ingress |Secure network entry points +|Oblivious DNS (IPv6) |Privacy-preserving DNS resolution +|GraphQL DNS APIs |Programmable domain resolution +|SurrealDB provenance graphs |Audit trails & data lineage +|=== + +==== Relationship to IndieWeb Security + +While *not* implementing IndieWeb protocols (Micropub, IndieAuth, +Webmention), indieweb2-bastion provides foundational security patterns +applicable to IndieWeb infrastructure: + +[cols=",",options="header",] +|=== +|indieweb2-bastion |IndieWeb Application +|Provenance graphs |Track Webmention verification chains +|Audit capabilities |Log IndieAuth token usage +|Bastion pattern |Rate limit Webmention endpoints +|Policy controls (Nickel) |Define allowed Micropub content +|=== + +==== Recommended Stack Architecture + +.... +┌─────────────────────────────────────────────────────────┐ +│ Full IndieWeb Stack │ +├─────────────────────────────────────────────────────────┤ +│ indieweb2-bastion │ Infrastructure layer │ +│ (network, DNS, audit)│ (bastion, provenance) │ +├───────────────────────┼─────────────────────────────────┤ +│ php-aegis │ Application layer │ +│ (validation, escaping)│ (Micropub, IndieAuth, Webmention)│ +├───────────────────────┼─────────────────────────────────┤ +│ sanctify-php │ Analysis layer │ +│ (static analysis) │ (find vulnerabilities) │ +└─────────────────────────────────────────────────────────┘ +.... + +''''' + +=== Final Summary: Integration Value Matrix + +[width="100%",cols="12%,29%,25%,34%",options="header",] +|=== +|Tool |WordPress Value |Non-WP Value |Unique Capability +|*php-aegis* |Low (WP has `+esc_*+`) |*High* |RDF/Turtle escaping +|*sanctify-php* |*High* (finds WP issues) |*High* |Taint tracking +|=== + +==== Key Learnings Across 5 Reports + +[arabic] +. *TurtleEscaper is the killer feature* - Fixed real vulnerabilities in +semantic web themes +. *GHC barrier is critical* - Confirmed in every sanctify-php +integration attempt +. *WordPress has comprehensive APIs* - php-aegis basic escaping is +redundant +. *php-aegis shines in framework gaps* - Security headers, extended +validators, RDF/Turtle +. *sanctify-php needs WordPress awareness* - Hook detection, REST API +patterns + +''''' + +=== Contact + +For questions about this integration or to coordinate between repos: - +php-aegis: https://github.com/hyperpolymath/php-aegis - sanctify-php: +https://github.com/hyperpolymath/sanctify-php - Integration tested in: +wp-sinople-theme, Zotpress, sinople-theme (×2) + +''''' + +_Generated from real-world WordPress integration experience (Reports +1-5)._ diff --git a/HANDOVER_SANCTIFY.md b/HANDOVER_SANCTIFY.md deleted file mode 100644 index d6b7aae..0000000 --- a/HANDOVER_SANCTIFY.md +++ /dev/null @@ -1,755 +0,0 @@ -# Handover Document: sanctify-php Integration Insights - -## Context - -This document summarizes findings from integrating `php-aegis` and `sanctify-php` into a WordPress semantic theme (wp-sinople-theme). It provides actionable recommendations for the `sanctify-php` team based on real-world usage patterns. - -## Role Clarification - -| Tool | Role | When Used | -|------|------|-----------| -| **php-aegis** | Runtime security library | During request handling (validation, sanitization, headers) | -| **sanctify-php** | Static analysis tool | During development/CI (find vulnerabilities before deploy) | - -These are **complementary**, not competing tools: -- `sanctify-php` finds the bugs -- `php-aegis` provides the fixes - -## Issues Discovered During Integration - -### 1. Haskell Toolchain Dependency - -**Problem**: `sanctify-php` requires GHC/Cabal to build, which is a significant barrier for PHP developers. - -**Impact**: Most PHP teams don't have Haskell expertise or toolchain installed. - -**Recommendations**: -- Provide pre-built binaries for Linux (x86_64, aarch64), macOS (Intel, Apple Silicon), Windows -- Create official Docker image: `ghcr.io/hyperpolymath/sanctify-php:latest` -- Consider GitHub Actions integration that runs analysis without local install -- Add installation via common package managers (Homebrew, apt, nix) - -**Example Docker usage**: -```bash -docker run --rm -v $(pwd):/workspace ghcr.io/hyperpolymath/sanctify-php analyze /workspace -``` - -### 2. PHP 8.x Syntax Support - -**Problem**: Parser may not handle all PHP 8.x syntax (enums, union types, named arguments, attributes, match expressions, constructor property promotion). - -**Test cases needed**: -```php -// Enums (PHP 8.1+) -enum Status: string { - case Draft = 'draft'; - case Published = 'published'; -} - -// Union types (PHP 8.0+) -function process(string|int $input): string|false { ... } - -// Attributes (PHP 8.0+) -#[Route('/api/users')] -class UserController { ... } - -// Constructor property promotion (PHP 8.0+) -class User { - public function __construct( - public readonly string $name, - private int $age = 0, - ) {} -} - -// Named arguments (PHP 8.0+) -htmlspecialchars(string: $input, flags: ENT_QUOTES); - -// Match expressions (PHP 8.0+) -$result = match($status) { - Status::Draft => 'Editing', - Status::Published => 'Live', -}; -``` - -**Recommendation**: Add PHP 8.x grammar rules and comprehensive test suite. - -### 3. RDF/Turtle Output Context Awareness - -**Problem**: Static analyzer doesn't detect RDF/Turtle injection vulnerabilities in semantic web themes. - -**Background**: Semantic WordPress themes output RDF Turtle format for linked data. Standard XSS detection won't catch Turtle-specific injection vectors. - -**Vulnerable pattern** (not currently detected): -```php -// DANGEROUS: addslashes() is insufficient for Turtle -$turtle = '<' . $uri . '> rdfs:label "' . addslashes($label) . '" .'; -``` - -**Attack vectors**: -```turtle -# Turtle escape sequences -\n \r \t \\ \" \uXXXX \UXXXXXXXX - -# IRI injection - owl:sameAs -``` - -**Recommendation**: Add detection rules for: -- `addslashes()` used in RDF/Turtle context -- Unescaped variables in Turtle string literals (`"..."`) -- Unescaped IRIs (`<...>`) -- Missing use of proper escaping functions - -**Suggested rule signatures**: -``` -turtle_string_injection: Detects unescaped user input in Turtle string literals -turtle_iri_injection: Detects unescaped user input in Turtle IRIs -rdf_semantic_injection: Detects potential semantic attacks via RDF -``` - -### 4. WordPress Integration Documentation - -**Problem**: No clear guidance for WordPress-specific vulnerability patterns. - -**WordPress-specific patterns to detect**: - -```php -// DANGEROUS: Direct $_GET/$_POST usage -echo $_GET['query']; // XSS - -// DANGEROUS: Missing nonce verification -if (isset($_POST['action'])) { ... } // CSRF - -// DANGEROUS: Direct SQL interpolation -$wpdb->query("SELECT * FROM users WHERE id = " . $_GET['id']); // SQLi - -// DANGEROUS: Unescaped output -echo $user_input; // Should use esc_html(), esc_attr(), etc. - -// DANGEROUS: Privileged action without capability check -add_action('wp_ajax_delete_user', 'delete_user_handler'); -function delete_user_handler() { - // Missing: current_user_can('delete_users') - wp_delete_user($_POST['user_id']); -} -``` - -**WordPress-specific safe patterns**: -```php -// Safe escaping functions -esc_html($text) -esc_attr($attr) -esc_url($url) -wp_kses($html, $allowed) -wp_kses_post($html) - -// Safe nonce verification -wp_verify_nonce($_POST['_wpnonce'], 'action_name') -check_admin_referer('action_name') - -// Safe capability checks -current_user_can('edit_posts') -``` - -**Recommendation**: Create WordPress-specific ruleset that: -- Detects missing `esc_*` function usage -- Detects missing nonce verification in form handlers -- Detects missing capability checks in AJAX handlers -- Recognizes WordPress sanitization functions as safe sinks - -### 5. IndieWeb/Micropub Pattern Detection - -**Problem**: No awareness of IndieWeb protocols (Micropub, IndieAuth, Webmention). - -**Patterns to detect**: - -```php -// DANGEROUS: Missing IndieAuth token verification -function handle_micropub($request) { - $content = $request['content']; // Unverified! - create_post($content); -} - -// DANGEROUS: Webmention SSRF -function verify_webmention($source) { - $response = wp_remote_get($source); // Can hit internal IPs -} - -// DANGEROUS: Micropub content injection -$mf2 = Mf2\parse($html, $source); -$content = $mf2['items'][0]['properties']['content'][0]; -echo $content; // Unsanitized from external source -``` - -**Recommendation**: Add rules for common IndieWeb vulnerability patterns. - -## Integration Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Development Workflow │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ -│ │ Developer │───▶│ sanctify-php │───▶│ Fix Code │ │ -│ │ Writes Code │ │ (Analysis) │ │ (Guidance) │ │ -│ └──────────────┘ └──────────────┘ └──────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌──────────────┐ │ -│ │ php-aegis │ │ -│ │ (Runtime) │ │ -│ └──────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - -## Recommended sanctify-php Output Format - -When `sanctify-php` detects a vulnerability, it should suggest the `php-aegis` fix: - -``` -VULNERABILITY: XSS in output context -FILE: theme/template.php:42 -CODE: echo $user_input; - -RECOMMENDATION: - Use php-aegis Sanitizer for proper encoding: - - Before: echo $user_input; - After: echo \PhpAegis\Sanitizer::html($user_input); - - Install: composer require hyperpolymath/php-aegis -``` - -## Priority Recommendations Summary - -| Priority | Issue | Effort | -|----------|-------|--------| -| P0 | Pre-built binaries / Docker image | Medium | -| P0 | PHP 8.x syntax support | High | -| P0 | Official GitHub Action (`sanctify-php-action`) | Medium | -| P1 | WordPress-specific rulesets | Medium | -| P1 | RDF/Turtle context detection | Medium | -| P1 | SARIF output for GitHub Security tab | Low | -| P2 | Incremental analysis (cache, scan changed files only) | High | -| P2 | IndieWeb protocol patterns | Low | -| P2 | php-aegis fix suggestions in output | Low | - ---- - -## Additional Findings (Report 2) - -### 6. GitHub Action Required - -**Problem**: No official GitHub Action for CI integration. - -**Impact**: Teams must write custom workflow configuration or use Docker manually. - -**Recommendation**: Create `hyperpolymath/sanctify-php-action` with: -```yaml -# .github/workflows/security.yml -- uses: hyperpolymath/sanctify-php-action@v1 - with: - path: ./src - config: sanctify.yml - sarif-output: results.sarif -``` - -### 7. SARIF Output for GitHub Integration - -**What Works Well**: SARIF format enables direct GitHub Security tab integration. - -**Enhancement**: Ensure SARIF output includes: -- Rule descriptions with OWASP references -- Severity levels mapped to GitHub's critical/high/medium/low -- Fix suggestions linking to php-aegis methods - -```json -{ - "runs": [{ - "tool": { "driver": { "name": "sanctify-php" } }, - "results": [{ - "ruleId": "xss-output", - "level": "error", - "message": { "text": "Unescaped output" }, - "fixes": [{ - "description": { "text": "Use PhpAegis\\Sanitizer::html()" } - }] - }] - }] -} -``` - -### 8. Incremental Analysis - -**Problem**: Full codebase scans are slow on large projects. - -**Recommendation**: -- Cache AST and taint analysis results -- On subsequent runs, only analyze changed files -- Invalidate cache when dependencies change -- Use file modification timestamps or git diff - -```bash -# First run: full analysis, build cache -sanctify analyze ./src --cache .sanctify-cache - -# Subsequent runs: incremental -sanctify analyze ./src --cache .sanctify-cache --incremental -``` - -### 9. Composer Plugin Wrapper - -**Problem**: PHP developers expect `composer require` installation. - -**Recommendation**: Create a Composer plugin that: -1. Downloads pre-built binary for platform -2. Provides `vendor/bin/sanctify` wrapper -3. Handles updates via Composer - -```bash -composer require --dev hyperpolymath/sanctify-php -vendor/bin/sanctify analyze ./src -``` - ---- - -## Standalone vs Combined Operation - -### Minimal Requirements for Each Tool - -**php-aegis standalone** (runtime protection): -- Zero dependencies (works everywhere PHP runs) -- Static methods for easy drop-in usage -- Works without sanctify-php installed - -**sanctify-php standalone** (static analysis): -- Pre-built binary (no Haskell needed) -- SARIF output for any CI system -- Works without php-aegis (just reports issues) - -### Combined Synergies - -When both tools are used together: - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ Combined Workflow │ -├─────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌────────────┐ ┌─────────────────┐ ┌──────────────────┐ │ -│ │ Write │──▶│ sanctify-php │──▶│ Fix with │ │ -│ │ Code │ │ (finds issues) │ │ php-aegis │ │ -│ └────────────┘ └─────────────────┘ └──────────────────┘ │ -│ │ │ │ -│ ▼ ▼ │ -│ ┌─────────────────────────────────────┐ │ -│ │ sanctify-php recognizes php-aegis │ │ -│ │ methods as "safe sinks" in taint │ │ -│ │ analysis, reducing false positives │ │ -│ └─────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────┘ -``` - -**Key synergy**: sanctify-php should recognize php-aegis sanitizers as safe: -```haskell --- sanctify-php taint rules -safeSinks = [ - "PhpAegis\\Sanitizer::html", - "PhpAegis\\Sanitizer::attr", - "PhpAegis\\Sanitizer::js", - "PhpAegis\\Sanitizer::css", - "PhpAegis\\Sanitizer::url", - "PhpAegis\\TurtleEscaper::string", - "PhpAegis\\TurtleEscaper::iri" -] -``` - ---- - -## Integration Metrics - -| Metric | Before Integration | After Integration | -|--------|-------------------|-------------------| -| Files with `strict_types` | 0 | 24 (100%) | -| PHP version | 7.4+ | 8.2+ | -| WordPress version | 5.8+ | 6.4+ | -| CI security checks | 0 | 4 | - ---- - -## Additional Findings (Report 3: Zotpress Plugin) - -### 10. GHC Barrier Confirmed (Critical) - -**Problem**: sanctify-php could not run on the Zotpress integration due to missing Haskell toolchain. - -**Impact**: This is now confirmed across multiple integration attempts. The Haskell build requirement is the #1 adoption barrier. - -**Immediate Recommendations**: -1. Provide pre-built binaries for: - - Linux x86_64 (static binary) - - Linux aarch64 (for ARM servers) - - macOS Intel - - macOS Apple Silicon - - Windows x64 -2. Publish Docker image: `ghcr.io/hyperpolymath/sanctify-php:latest` -3. Create GitHub Action that uses the Docker image internally - -**Workaround Used**: Manual analysis using sanctify-php's documented detection patterns. - -### 11. WordPress Security API Overlap - -**Finding**: When analyzing mature WordPress plugins (like Zotpress), they already follow WordPress security best practices using core functions. - -**WordPress provides equivalent security functions**: - -| php-aegis | WordPress Equivalent | Notes | -|-----------|---------------------|-------| -| `Validator::email()` | `is_email()` | WP version is more permissive | -| `Validator::url()` | `wp_http_validate_url()` | WP has SSL enforcement | -| `Sanitizer::html()` | `esc_html()` | Identical functionality | -| `Sanitizer::attr()` | `esc_attr()` | Identical functionality | -| `Sanitizer::js()` | `esc_js()` | WP version is context-aware | -| `Sanitizer::url()` | `esc_url()` | WP handles protocols | -| `Sanitizer::stripTags()` | `wp_strip_all_tags()` | WP handles more edge cases | - -**What sanctify-php should detect**: -- Direct use of raw PHP functions instead of WordPress equivalents -- `echo $var` instead of `echo esc_html($var)` -- `header('Location: ...')` instead of `wp_redirect()` -- Missing `exit;` after redirect - -**sanctify-php rule suggestions**: -```haskell --- WordPress-specific rules -wpRules = [ - ("use_wp_redirect", "header\\s*\\(\\s*['\"]Location", "Use wp_redirect() instead of header()"), - ("missing_exit_redirect", "wp_redirect\\([^;]+\\);(?!\\s*exit)", "Add exit; after wp_redirect()"), - ("raw_echo", "echo\\s+\\$(?!esc_)", "Escape output with esc_html()/esc_attr()"), - ("direct_superglobal", "\\$_(GET|POST|REQUEST)\\[", "Sanitize superglobals before use") -] -``` - -### 12. Target Audience Clarification Needed - -**Finding**: php-aegis value proposition is unclear for WordPress users. - -**Recommended positioning for sanctify-php**: - -When sanctify-php detects issues in WordPress code, suggest: -1. **First choice**: WordPress native function (if available) -2. **Second choice**: php-aegis function (for gaps WordPress doesn't cover) - -``` -VULNERABILITY: Unescaped output -FILE: plugin.php:42 -CODE: echo $user_input; - -RECOMMENDATION: - WordPress: echo esc_html($user_input); - Or php-aegis: echo \PhpAegis\Sanitizer::html($user_input); -``` - -### 13. WordPress-Unique Security Patterns - -**What sanctify-php should understand about WordPress**: - -```php -// WordPress-specific security patterns - -// 1. ABSPATH protection (must be at top of every PHP file) -if (!defined('ABSPATH')) exit; - -// 2. Nonce verification for forms -check_admin_referer('action_name'); -wp_verify_nonce($_POST['nonce'], 'action_name'); - -// 3. Capability checks for privileged actions -if (!current_user_can('manage_options')) return; - -// 4. Prepared statements for database -$wpdb->prepare("SELECT * FROM table WHERE id = %d", $id); - -// 5. Safe redirect -wp_safe_redirect($url); -exit; -``` - -**Detection rules needed**: -- Missing ABSPATH check at file start -- Form handlers without nonce verification -- AJAX handlers without capability checks -- Missing `exit;` after redirects - ---- - -## Additional Findings (Report 4: sinople-theme Full Integration) - -### 14. Successful Integration Pattern - -**What Worked**: Full integration with WordPress theme including: -- Function wrappers: `sinople_aegis_html()`, `sinople_aegis_attr()`, `sinople_aegis_json()` -- Validation wrappers: `sinople_aegis_validate_*()` functions -- RDF/Turtle feed endpoint using `TurtleEscaper` (unique value!) -- Graceful fallback to WordPress functions when php-aegis unavailable -- Unit tests for the integration - -**Key Success**: TurtleEscaper proved its unique value by enabling a `/feed/turtle/` endpoint. - -### 15. sanctify-php False Positives Identified - -**Issues to address**: - -1. **UnsafeRedirect false positive**: When `exit;` is on the next line -```php -// This triggers false positive: -wp_redirect($url); -exit; - -// sanctify-php expects: -wp_redirect($url); exit; -``` - -2. **MissingTextDomain false positive**: Flags WordPress core functions -```php -// This may be flagged incorrectly: -__('Text', 'theme-domain'); // OK -_e('Text', 'theme-domain'); // OK -esc_html__('Text'); // May flag - but sometimes domain is optional -``` - -**Recommendation**: Add configuration options: -```yaml -# sanctify.yml -rules: - UnsafeRedirect: - allow_next_line_exit: true - MissingTextDomain: - ignore_core_functions: true -``` - -### 16. PHP 8.1+ Syntax Verification Needed - -**Concern**: Parser may not handle modern PHP syntax. - -**Test cases to verify**: -```php -// Nullsafe operator (PHP 8.0+) -$value = $object?->property?->method(); - -// Match expression (PHP 8.0+) -$result = match($type) { - 'html' => Sanitizer::html($input), - 'js' => Sanitizer::js($input), - default => $input, -}; - -// Constructor property promotion (PHP 8.0+) -public function __construct( - private readonly string $name, -) {} - -// First-class callable syntax (PHP 8.1+) -$fn = Sanitizer::html(...); -``` - -### 17. Guix Export Documentation - -**Issue**: Guix package export documentation is incomplete. - -**Recommendation**: Add to sanctify-php docs: -```scheme -;; guix.scm -(use-modules (guix packages) - (guix git-download) - (guix build-system haskell)) - -(package - (name "sanctify-php") - (version "0.1.0") - (source (git-reference - (url "https://github.com/hyperpolymath/sanctify-php") - (commit (string-append "v" version)))) - (build-system haskell-build-system) - (synopsis "PHP security static analyzer") - (license license:agpl3+)) -``` - ---- - -## php-aegis Self-Identified Issues (Report 4) - -These issues were discovered during sinople-theme integration: - -| Issue | Status | Resolution | -|-------|--------|------------| -| `Headers::secure()` missing `permissionsPolicy()` | ✅ Fixed | Added in this PR | -| `php-aegis-compat` package doesn't exist | 📋 Planned | Create separate repo | -| Not published on Packagist | 📋 Planned | Publish after v0.2.0 | -| WordPress mu-plugin adapter not implemented | 📋 Planned | Phase 7 roadmap | - ---- - -## Additional Findings (Report 5: Sinople Theme - Critical Vulnerability Fixed) - -### 18. TurtleEscaper Fixed Real Vulnerability - -**Critical Finding**: The theme was using `addslashes()` for RDF Turtle escaping - this is SQL escaping, NOT Turtle escaping. This was a real RDF injection vulnerability. - -**Before (vulnerable)**: -```php -// DANGEROUS: addslashes() is SQL escaping, not Turtle escaping! -$turtle = '"' . addslashes($label) . '"@en'; -``` - -**After (fixed)**: -```php -use PhpAegis\TurtleEscaper; -$turtle = TurtleEscaper::literal($label, language: 'en'); -``` - -**This validates TurtleEscaper as the #1 unique value proposition of php-aegis.** - -### 19. Security Fixes Applied in Real Integration - -| Severity | Issue | Fix Applied | -|----------|-------|-------------| -| CRITICAL | `addslashes()` for Turtle | `TurtleEscaper::literal()` | -| CRITICAL | IRI interpolation | `Validator::url()` + error handling | -| HIGH | URL validation via `strpos()` | `parse_url()` host comparison | -| HIGH | Unsanitized Micropub input | `sanitize_text_field()` + `wp_kses_post()` | -| MEDIUM | No security headers | `Headers::secure()` equivalent | -| MEDIUM | No rate limiting | 1-min rate limit for Webmentions | -| LOW | Missing `strict_types` | Added to all files | - -### 20. New Detection Rules for sanctify-php - -**RDF Turtle as Distinct Output Context**: - -sanctify-php should recognize Turtle output contexts and flag: -```haskell --- RDF Turtle detection rules -turtleRules = [ - -- Dangerous: SQL escaping in Turtle context - ("turtle_addslashes", "addslashes\\s*\\([^)]+\\).*['\"]@[a-z]{2}", - "Use TurtleEscaper::literal() instead of addslashes() for Turtle"), - - -- Dangerous: String interpolation in Turtle IRI - ("turtle_iri_interp", "<.*\\$[a-zA-Z_].*>", - "Use TurtleEscaper::iri() for Turtle IRIs"), - - -- Dangerous: Raw variable in Turtle string - ("turtle_string_raw", "\"\\$[a-zA-Z_][^\"]*\"@[a-z]", - "Use TurtleEscaper::string() for Turtle literals") -] -``` - -**WordPress REST API Pattern Recognition**: -```haskell --- WordPress REST API rules -restRules = [ - ("rest_missing_permission", "register_rest_route.*permission_callback.*__return_true", - "REST routes should verify permissions"), - - ("rest_raw_param", "\\$request\\[.*\\](?!.*sanitize)", - "Sanitize REST API parameters") -] -``` - -**WordPress Hook Detection** (reduce false positives): -```haskell --- Functions defined via add_action/add_filter are called by WordPress -wpHookFunctions = extractFunctionsFrom [ - "add_action\\s*\\([^,]+,\\s*['\"]([^'\"]+)", - "add_filter\\s*\\([^,]+,\\s*['\"]([^'\"]+)" -] --- These should not be flagged as "unused functions" -``` - -### 21. php-aegis Enhancement Requests - -From this integration: - -| Request | Priority | Notes | -|---------|----------|-------| -| WordPress nonce validator | Medium | `Validator::wpNonce($nonce, $action)` | -| WordPress capability checker | Medium | `Validator::wpCapability($cap)` | -| TurtleEscaper case sensitivity docs | Low | Language tags should be lowercase | -| SPDX identifier validator | Low | `Validator::spdx($identifier)` | -| Headers + WordPress integration docs | Medium | How to use with `wp_headers` filter | - ---- - -## Related Project: indieweb2-bastion - -The [indieweb2-bastion](https://github.com/hyperpolymath/indieweb2-bastion) repository provides infrastructure-layer security that complements php-aegis and sanctify-php at the application layer. - -### What indieweb2-bastion Does - -| Feature | Purpose | -|---------|---------| -| Hardened bastion ingress | Secure network entry points | -| Oblivious DNS (IPv6) | Privacy-preserving DNS resolution | -| GraphQL DNS APIs | Programmable domain resolution | -| SurrealDB provenance graphs | Audit trails & data lineage | - -### Relationship to IndieWeb Security - -While **not** implementing IndieWeb protocols (Micropub, IndieAuth, Webmention), indieweb2-bastion provides foundational security patterns applicable to IndieWeb infrastructure: - -| indieweb2-bastion | IndieWeb Application | -|-------------------|---------------------| -| Provenance graphs | Track Webmention verification chains | -| Audit capabilities | Log IndieAuth token usage | -| Bastion pattern | Rate limit Webmention endpoints | -| Policy controls (Nickel) | Define allowed Micropub content | - -### Recommended Stack Architecture - -``` -┌─────────────────────────────────────────────────────────┐ -│ Full IndieWeb Stack │ -├─────────────────────────────────────────────────────────┤ -│ indieweb2-bastion │ Infrastructure layer │ -│ (network, DNS, audit)│ (bastion, provenance) │ -├───────────────────────┼─────────────────────────────────┤ -│ php-aegis │ Application layer │ -│ (validation, escaping)│ (Micropub, IndieAuth, Webmention)│ -├───────────────────────┼─────────────────────────────────┤ -│ sanctify-php │ Analysis layer │ -│ (static analysis) │ (find vulnerabilities) │ -└─────────────────────────────────────────────────────────┘ -``` - ---- - -## Final Summary: Integration Value Matrix - -| Tool | WordPress Value | Non-WP Value | Unique Capability | -|------|----------------|--------------|-------------------| -| **php-aegis** | Low (WP has `esc_*`) | **High** | RDF/Turtle escaping | -| **sanctify-php** | **High** (finds WP issues) | **High** | Taint tracking | - -### Key Learnings Across 5 Reports - -1. **TurtleEscaper is the killer feature** - Fixed real vulnerabilities in semantic web themes -2. **GHC barrier is critical** - Confirmed in every sanctify-php integration attempt -3. **WordPress has comprehensive APIs** - php-aegis basic escaping is redundant -4. **php-aegis shines in framework gaps** - Security headers, extended validators, RDF/Turtle -5. **sanctify-php needs WordPress awareness** - Hook detection, REST API patterns - ---- - -## Contact - -For questions about this integration or to coordinate between repos: -- php-aegis: https://github.com/hyperpolymath/php-aegis -- sanctify-php: https://github.com/hyperpolymath/sanctify-php -- Integration tested in: wp-sinople-theme, Zotpress, sinople-theme (×2) - ---- - -*Generated from real-world WordPress integration experience (Reports 1-5).* diff --git a/PHP_AEGIS_ANALYSIS_SUMMARY.adoc b/PHP_AEGIS_ANALYSIS_SUMMARY.adoc new file mode 100644 index 0000000..e802ade --- /dev/null +++ b/PHP_AEGIS_ANALYSIS_SUMMARY.adoc @@ -0,0 +1,456 @@ +== php-aegis Analysis Summary + +*Date*: 2026-01-22 *Analysis Type*: Comprehensive codebase assessment +and development planning *Current Status*: 65% complete → Target 95% +(Production Ready) + +''''' + +=== Executive Summary + +php-aegis is a PHP 8.1+ security and hardening toolkit providing input +validation, sanitization, and security utilities. This analysis reveals +a solid foundation with unique capabilities (RDF/Turtle escaping) and +identifies a clear path to production readiness. + +==== Key Findings + +*Strengths*: 1. *TurtleEscaper is a killer feature* - Only PHP library +with W3C-compliant RDF Turtle escaping (fixed real vulnerabilities) 2. +*Zero dependencies* - Works everywhere PHP 8.1+ runs 3. *Comprehensive +test coverage* - 4 test files covering all core functionality 4. *Modern +PHP practices* - strict_types, static methods, PSR-12 compliant 5. +*Well-documented core* - README, ROADMAP, POSITIONING, SECURE_DEFAULTS + +*Gaps*: 1. *WordPress integration missing* - No adapter functions or +MU-plugin template (0%) 2. *Not published* - Not available on Packagist +yet (0%) 3. *Documentation incomplete* - API reference, integration +guides missing (30%) 4. *IndieWeb security* - Micropub, IndieAuth, +Webmention validators not implemented (0%) 5. *Rate limiting* - Token +bucket implementation not started (0%) + +''''' + +=== Current State (65% Complete) + +==== Code Metrics + +[cols=",",options="header",] +|=== +|Metric |Value +|*Total Lines* |3,173 +|*Source Files* |5 +|*Test Files* |4 +|*Test Coverage* |~85% (estimated) +|*Dependencies* |0 (runtime) +|*PHP Version* |8.1+ +|*License* |MIT OR PMPL-1.0-or-later (SPDX) +|=== + +==== Implemented Features (100% Complete) + +===== 1. Validator Class (247 lines) + +*17 validation methods*: - Network: `+email()+`, `+url()+`, +`+httpsUrl()+`, `+ip()+`, `+ipv4()+`, `+ipv6()+`, `+hostname()+`, +`+domain()+` - Format: `+uuid()+`, `+slug()+`, `+json()+`, `+int()+`, +`+semver()+`, `+iso8601()+`, `+hexColor()+` - Security: +`+noNullBytes()+`, `+safeFilename()+`, `+printable()+` + +*Quality*: - ✅ All methods static - ✅ SPDX headers - ✅ strict_types - +✅ Comprehensive tests + +===== 2. Sanitizer Class (110 lines) + +*10 sanitization methods*: - Context-aware: `+html()+`, `+attr()+`, +`+js()+`, `+css()+`, `+url()+`, `+json()+` - Utility: `+stripTags()+`, +`+removeNullBytes()+`, `+filename()+` + +*Quality*: - ✅ ENT_QUOTES | ENT_HTML5 flags - ✅ JSON_HEX_* flags for +security - ✅ All contexts covered - ✅ Comprehensive tests + +===== 3. TurtleEscaper Class (6KB) ⭐ UNIQUE VALUE + +*RDF Turtle escaping* - No other PHP library does this! - `+string()+` - +Escape Turtle string literals - `+iri()+` - Escape/validate Turtle IRIs +- `+literal()+` - Complete literal with language/datatype - `+triple()+` +- Build complete RDF triples + +*Real-World Impact*: - Fixed critical RDF injection vulnerability in +wp-sinople-theme - Enabled `+/feed/turtle/+` endpoint for semantic +themes - Validated by real WordPress integration + +*Quality*: - ✅ W3C-compliant - ✅ Handles all escape sequences (, \, ", +, ) - ✅ Comprehensive tests (14KB test file) + +===== 4. Headers Class (7KB) + +*Security headers*: - `+contentSecurityPolicy()+` - CSP directives - +`+strictTransportSecurity()+` - HSTS with preload - `+frameOptions()+` - +X-Frame-Options - `+referrerPolicy()+` - Referrer-Policy - +`+permissionsPolicy()+` - Permissions-Policy - `+secure()+` - Apply all +recommended headers at once + +*Quality*: - ✅ Sensible defaults - ✅ One-line usage +(`+Headers::secure()+`) - ✅ WordPress-compatible (can use with +`+send_headers+` action) + +===== 5. Crypto Utilities (17KB) + +*Cryptographic functions*: - Secure random generation - Password hashing +recommendations - Key derivation patterns + +*Status*: Implementation details not fully analyzed (large file) + +===== 6. Test Suite (67KB) + +*4 comprehensive test files*: - `+ValidatorTest.php+` (20KB) - All 17 +validators - `+SanitizerTest.php+` (15KB) - All 10 sanitizers - +`+HeadersTest.php+` (17KB) - All header methods - +`+TurtleEscaperTest.php+` (14KB) - All Turtle methods + +*Quality*: - ✅ PHPUnit configured - ✅ Edge cases covered - ✅ Attack +vector testing + +''''' + +=== Gap Analysis + +==== Critical Gaps (Blocking Production Use) + +===== 1. WordPress Integration (0%) + +*Impact*: WordPress is largest PHP ecosystem *What’s Missing*: - Adapter +functions (`+aegis_html()+`, `+aegis_attr()+`, etc.) - MU-plugin +template for easy installation - Integration guide with examples - +Testing with real WordPress themes/plugins + +*Recommendation*: High priority - WordPress is primary target audience + +===== 2. Packagist Publication (0%) + +*Impact*: Cannot install via `+composer require+` *What’s Missing*: - +Registration on packagist.org - GitHub webhook configuration - Version +tagging for releases + +*Recommendation*: Critical for adoption - blocks all users + +===== 3. Documentation Gaps (30%) + +*What Exists*: - ✅ README.adoc (comprehensive overview) - ✅ +ROADMAP_PRIORITY.md (integration-informed) - ✅ POSITIONING.md +(differentiation strategy) - ✅ SECURE_DEFAULTS.md (OWASP Top 10 +mapping) - ✅ HANDOVER_SANCTIFY.md (integration findings) + +*What’s Missing*: - ❌ API reference (method signatures, parameters, +examples) - ❌ User guide (installation, quick start, troubleshooting) - +❌ WordPress integration guide - ❌ IndieWeb integration guide - ❌ +Real-world examples + +*Recommendation*: Medium priority - users can figure out API from tests + +==== Feature Gaps (Non-Blocking) + +===== 4. IndieWeb Security (0%) + +*What’s Planned*: - Micropub content validator - IndieAuth token +validator - Webmention SSRF prevention + +*Priority*: Medium - niche use case but differentiator + +===== 5. Rate Limiting (0%) + +*What’s Planned*: - Token bucket implementation - File store +(production, no Redis) - Memory store (development) + +*Priority*: Medium - common need but alternatives exist + +===== 6. Framework Adapters (0%) + +*What’s Planned*: - Laravel service provider - Symfony bundle + +*Priority*: Low - current API is already usable + +''''' + +=== Unique Value Proposition + +==== What php-aegis Does That No One Else Does + +[cols=",,,,",options="header",] +|=== +|Feature |WordPress |Laravel |Symfony |php-aegis +|*RDF/Turtle escaping* |❌ |❌ |❌ |✅ UNIQUE +|Security headers helper |❌ |Partial |Partial |✅ +|IndieWeb validation |❌ |❌ |❌ |✅ Planned +|Zero dependencies |N/A |❌ |❌ |✅ +|PHP 8.1+ strict types |❌ |❌ |❌ |✅ +|Rate limiting (no Redis) |❌ |❌ |❌ |✅ Planned +|=== + +==== Real-World Validation + +From HANDOVER_SANCTIFY.md: + +*Critical Finding*: wp-sinople-theme was using `+addslashes()+` for RDF +Turtle escaping - this is SQL escaping, NOT Turtle escaping. This was a +*real RDF injection vulnerability*. + +[source,php] +---- +// BEFORE (vulnerable) +$turtle = '"' . addslashes($label) . '"@en'; // WRONG! SQL escaping ≠ Turtle escaping + +// AFTER (fixed with php-aegis) +use PhpAegis\TurtleEscaper; +$turtle = TurtleEscaper::literal($label, language: 'en'); // ✅ Correct W3C-compliant escaping +---- + +*This validates TurtleEscaper as the #1 unique value proposition.* + +''''' + +=== Integration with sanctify-php + +php-aegis (runtime protection) and sanctify-php (static analysis) are +complementary: + +[width="100%",cols="27%,26%,47%",options="header",] +|=== +|Tool |Role |When Used +|*sanctify-php* |Static analysis |During development/CI (finds the bugs) + +|*php-aegis* |Runtime security |During request handling (provides the +fixes) +|=== + +==== Synergy: Safe Sink Recognition + +*sanctify-php should recognize php-aegis methods as "`safe sinks`"* in +taint analysis to reduce false positives: + +[source,haskell] +---- +-- sanctify-php taint rules (recommended) +safeSinks = [ + "PhpAegis\\Sanitizer::html", + "PhpAegis\\Sanitizer::attr", + "PhpAegis\\Sanitizer::js", + "PhpAegis\\Sanitizer::css", + "PhpAegis\\Sanitizer::url", + "PhpAegis\\TurtleEscaper::string", + "PhpAegis\\TurtleEscaper::iri", + "PhpAegis\\TurtleEscaper::literal" +] +---- + +==== Coordinated Workflow + +.... +┌─────────────────────────────────────────────────────────┐ +│ Development Workflow │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ┌────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Write │──▶│ sanctify-php │──▶│ Fix with │ │ +│ │ Code │ │ (finds issues)│ │ php-aegis │ │ +│ └────────────┘ └──────────────┘ └──────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────┐ │ +│ │ sanctify-php recognizes │ │ +│ │ php-aegis as safe, reducing │ │ +│ │ false positives │ │ +│ └─────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────┘ +.... + +''''' + +=== Development Roadmap Summary + +*Path to 95% (Production Ready)*: + +[width="100%",cols="23%,37%,40%",options="header",] +|=== +|Phase |Completion |Description +|*Phase 1: WordPress Integration* |65% → 72% |Adapter functions, +MU-plugin, tests, guide + +|*Phase 2: IndieWeb Security* |72% → 78% |Micropub, IndieAuth, +Webmention validators + +|*Phase 3: Rate Limiting* |78% → 83% |Token bucket, file/memory stores + +|*Phase 4: Documentation* |83% → 90% |API reference, user guide, +integration guides + +|*Phase 5: Real-World Validation* |90% → 95% |Test with 3 themes + 3 +plugins, create report + +|*Phase 6: Deployment* |95% → 100% |Packagist, Docker, GitHub Action +|=== + +*See PHP_AEGIS_DEVELOPMENT_PLAN.md for detailed implementation steps.* + +''''' + +=== Comparison with sanctify-php Journey + +Both projects followed similar paths to production readiness: + +[cols=",,",options="header",] +|=== +|Metric |sanctify-php |php-aegis +|*Starting Point* |40% |65% +|*Target* |95% |95% +|*Gain Needed* |55 points |30 points +|*Key Milestone* |Parser completion |WordPress integration +|*Unique Feature* |WordPress-native analysis |RDF/Turtle escaping +|*Test Suite* |Comprehensive (Hspec) |Comprehensive (PHPUnit) +|*Documentation* |60+ pages |Target: 200+ pages +|*Real-World Validation* |WordPress plugins |Pending +|=== + +''''' + +=== Immediate Next Steps + +==== Priority 1: WordPress Integration (High Impact) + +[arabic] +. Implement adapter functions in `+src/WordPress/Adapter.php+` +. Create MU-plugin template in `+docs/wordpress/aegis-mu-plugin.php+` +. Write WordPress integration tests in +`+tests/WordPress/AdapterTest.php+` +. Create comprehensive WordPress guide in +`+docs/wordpress/WORDPRESS_INTEGRATION.md+` +. Test with 2 real WordPress themes/plugins + +*Why First*: WordPress is the largest PHP ecosystem and primary target +audience + +==== Priority 2: Publish to Packagist (Highest Impact) + +[arabic] +. Register on packagist.org +. Configure GitHub webhook +. Tag version 0.2.0 release +. Update README with installation instructions +. Announce on PHP communities + +*Why Second*: Blocks ALL adoption - must be installable + +==== Priority 3: Complete Documentation (Medium Impact) + +[arabic] +. Write API reference (100 pages) +. Write user guide (50 pages) +. Enhance security guide (OWASP examples) +. Create integration examples + +*Why Third*: Users can figure out API from tests, but docs improve +adoption + +''''' + +=== Success Criteria for Production Ready (95%) + +==== Code Quality + +* [ ] 100% test coverage for core functionality +* [ ] PHPStan level 9 (strict) +* [ ] PHP-CS-Fixer (PSR-12) +* [ ] Zero critical security issues + +==== Documentation + +* [ ] 200+ pages of comprehensive docs +* [ ] 50+ working code examples +* [ ] 3+ framework integration guides +* [ ] 10+ real-world use cases + +==== Deployment + +* [ ] Published on Packagist +* [ ] Docker image on GHCR +* [ ] GitHub Action for CI integration +* [ ] Pre-built binaries (N/A for PHP) + +==== Validation + +* [ ] Tested with 3 WordPress themes +* [ ] Tested with 3 WordPress plugins +* [ ] Zero false positives in real code +* [ ] Test report documenting findings + +==== Adoption Metrics + +* [ ] 100+ Packagist installs/month +* [ ] 50+ GitHub stars +* [ ] 10+ contributors +* [ ] 5+ integration examples in the wild + +''''' + +=== Related Projects + +[width="100%",cols="30%,45%,25%",options="header",] +|=== +|Project |Relationship |Status +|*sanctify-php* |Static analysis (finds bugs) |95% complete +(production-ready) + +|*indieweb2-bastion* |Infrastructure security |70% complete (GraphQL DNS +pending) + +|*wp-audit-toolkit* |WordPress auditing |Unknown + +|*proof-of-work* |Spam prevention |Production +|=== + +''''' + +=== Key Learnings from sanctify-php + +Applying lessons from sanctify-php’s journey to 95%: + +[arabic] +. *Real-world validation is critical* - Test against actual WordPress +plugins/themes +. *Documentation matters* - 60+ pages made sanctify-php production-ready +. *Test coverage is non-negotiable* - Comprehensive test suite builds +confidence +. *Unique features win* - TurtleEscaper is to php-aegis what +WordPress-native analysis is to sanctify-php +. *Publish early* - Don’t wait for 100% - publish at 95% + +''''' + +=== Conclusion + +php-aegis has a *solid foundation at 65% with unique capabilities* +(RDF/Turtle escaping that fixed real vulnerabilities). With focused +effort on WordPress integration, documentation, and publishing, it can +reach *95% production-ready status* and serve as the runtime complement +to sanctify-php’s static analysis. + +*The TurtleEscaper feature alone justifies php-aegis’s existence* - it’s +the only PHP library that properly handles RDF Turtle escaping, as +validated by fixing a real critical vulnerability in wp-sinople-theme. + +*Recommended approach*: Follow the same comprehensive methodology used +for sanctify-php: 1. Complete core functionality (WordPress, IndieWeb, +rate limiting) 2. Comprehensive documentation (200+ pages) 3. Real-world +validation (test against actual WordPress code) 4. Professional +deployment (Packagist, Docker, GitHub Action) + +*Timeline Philosophy*: Per project guidelines, no time estimates +provided. Work proceeds based on: - User demand (GitHub issues) - +Security criticality - Contributor availability + +''''' + +_Analysis completed 2026-01-22. Ready to proceed with Phase 1: WordPress +Integration._ diff --git a/PHP_AEGIS_ANALYSIS_SUMMARY.md b/PHP_AEGIS_ANALYSIS_SUMMARY.md deleted file mode 100644 index 2c38c01..0000000 --- a/PHP_AEGIS_ANALYSIS_SUMMARY.md +++ /dev/null @@ -1,413 +0,0 @@ -# php-aegis Analysis Summary - -**Date**: 2026-01-22 -**Analysis Type**: Comprehensive codebase assessment and development planning -**Current Status**: 65% complete → Target 95% (Production Ready) - ---- - -## Executive Summary - -php-aegis is a PHP 8.1+ security and hardening toolkit providing input validation, sanitization, and security utilities. This analysis reveals a solid foundation with unique capabilities (RDF/Turtle escaping) and identifies a clear path to production readiness. - -### Key Findings - -**Strengths**: -1. **TurtleEscaper is a killer feature** - Only PHP library with W3C-compliant RDF Turtle escaping (fixed real vulnerabilities) -2. **Zero dependencies** - Works everywhere PHP 8.1+ runs -3. **Comprehensive test coverage** - 4 test files covering all core functionality -4. **Modern PHP practices** - strict_types, static methods, PSR-12 compliant -5. **Well-documented core** - README, ROADMAP, POSITIONING, SECURE_DEFAULTS - -**Gaps**: -1. **WordPress integration missing** - No adapter functions or MU-plugin template (0%) -2. **Not published** - Not available on Packagist yet (0%) -3. **Documentation incomplete** - API reference, integration guides missing (30%) -4. **IndieWeb security** - Micropub, IndieAuth, Webmention validators not implemented (0%) -5. **Rate limiting** - Token bucket implementation not started (0%) - ---- - -## Current State (65% Complete) - -### Code Metrics - -| Metric | Value | -|--------|-------| -| **Total Lines** | 3,173 | -| **Source Files** | 5 | -| **Test Files** | 4 | -| **Test Coverage** | ~85% (estimated) | -| **Dependencies** | 0 (runtime) | -| **PHP Version** | 8.1+ | -| **License** | MIT OR PMPL-1.0-or-later (SPDX) | - -### Implemented Features (100% Complete) - -#### 1. Validator Class (247 lines) -**17 validation methods**: -- Network: `email()`, `url()`, `httpsUrl()`, `ip()`, `ipv4()`, `ipv6()`, `hostname()`, `domain()` -- Format: `uuid()`, `slug()`, `json()`, `int()`, `semver()`, `iso8601()`, `hexColor()` -- Security: `noNullBytes()`, `safeFilename()`, `printable()` - -**Quality**: -- ✅ All methods static -- ✅ SPDX headers -- ✅ strict_types -- ✅ Comprehensive tests - -#### 2. Sanitizer Class (110 lines) -**10 sanitization methods**: -- Context-aware: `html()`, `attr()`, `js()`, `css()`, `url()`, `json()` -- Utility: `stripTags()`, `removeNullBytes()`, `filename()` - -**Quality**: -- ✅ ENT_QUOTES | ENT_HTML5 flags -- ✅ JSON_HEX_* flags for security -- ✅ All contexts covered -- ✅ Comprehensive tests - -#### 3. TurtleEscaper Class (6KB) ⭐ UNIQUE VALUE -**RDF Turtle escaping** - No other PHP library does this! -- `string()` - Escape Turtle string literals -- `iri()` - Escape/validate Turtle IRIs -- `literal()` - Complete literal with language/datatype -- `triple()` - Build complete RDF triples - -**Real-World Impact**: -- Fixed critical RDF injection vulnerability in wp-sinople-theme -- Enabled `/feed/turtle/` endpoint for semantic themes -- Validated by real WordPress integration - -**Quality**: -- ✅ W3C-compliant -- ✅ Handles all escape sequences (\n, \r, \t, \\, \", \uXXXX, \UXXXXXXXX) -- ✅ Comprehensive tests (14KB test file) - -#### 4. Headers Class (7KB) -**Security headers**: -- `contentSecurityPolicy()` - CSP directives -- `strictTransportSecurity()` - HSTS with preload -- `frameOptions()` - X-Frame-Options -- `referrerPolicy()` - Referrer-Policy -- `permissionsPolicy()` - Permissions-Policy -- `secure()` - Apply all recommended headers at once - -**Quality**: -- ✅ Sensible defaults -- ✅ One-line usage (`Headers::secure()`) -- ✅ WordPress-compatible (can use with `send_headers` action) - -#### 5. Crypto Utilities (17KB) -**Cryptographic functions**: -- Secure random generation -- Password hashing recommendations -- Key derivation patterns - -**Status**: Implementation details not fully analyzed (large file) - -#### 6. Test Suite (67KB) -**4 comprehensive test files**: -- `ValidatorTest.php` (20KB) - All 17 validators -- `SanitizerTest.php` (15KB) - All 10 sanitizers -- `HeadersTest.php` (17KB) - All header methods -- `TurtleEscaperTest.php` (14KB) - All Turtle methods - -**Quality**: -- ✅ PHPUnit configured -- ✅ Edge cases covered -- ✅ Attack vector testing - ---- - -## Gap Analysis - -### Critical Gaps (Blocking Production Use) - -#### 1. WordPress Integration (0%) -**Impact**: WordPress is largest PHP ecosystem -**What's Missing**: -- Adapter functions (`aegis_html()`, `aegis_attr()`, etc.) -- MU-plugin template for easy installation -- Integration guide with examples -- Testing with real WordPress themes/plugins - -**Recommendation**: High priority - WordPress is primary target audience - -#### 2. Packagist Publication (0%) -**Impact**: Cannot install via `composer require` -**What's Missing**: -- Registration on packagist.org -- GitHub webhook configuration -- Version tagging for releases - -**Recommendation**: Critical for adoption - blocks all users - -#### 3. Documentation Gaps (30%) -**What Exists**: -- ✅ README.adoc (comprehensive overview) -- ✅ ROADMAP_PRIORITY.md (integration-informed) -- ✅ POSITIONING.md (differentiation strategy) -- ✅ SECURE_DEFAULTS.md (OWASP Top 10 mapping) -- ✅ HANDOVER_SANCTIFY.md (integration findings) - -**What's Missing**: -- ❌ API reference (method signatures, parameters, examples) -- ❌ User guide (installation, quick start, troubleshooting) -- ❌ WordPress integration guide -- ❌ IndieWeb integration guide -- ❌ Real-world examples - -**Recommendation**: Medium priority - users can figure out API from tests - -### Feature Gaps (Non-Blocking) - -#### 4. IndieWeb Security (0%) -**What's Planned**: -- Micropub content validator -- IndieAuth token validator -- Webmention SSRF prevention - -**Priority**: Medium - niche use case but differentiator - -#### 5. Rate Limiting (0%) -**What's Planned**: -- Token bucket implementation -- File store (production, no Redis) -- Memory store (development) - -**Priority**: Medium - common need but alternatives exist - -#### 6. Framework Adapters (0%) -**What's Planned**: -- Laravel service provider -- Symfony bundle - -**Priority**: Low - current API is already usable - ---- - -## Unique Value Proposition - -### What php-aegis Does That No One Else Does - -| Feature | WordPress | Laravel | Symfony | php-aegis | -|---------|-----------|---------|---------|-----------| -| **RDF/Turtle escaping** | ❌ | ❌ | ❌ | ✅ UNIQUE | -| Security headers helper | ❌ | Partial | Partial | ✅ | -| IndieWeb validation | ❌ | ❌ | ❌ | ✅ Planned | -| Zero dependencies | N/A | ❌ | ❌ | ✅ | -| PHP 8.1+ strict types | ❌ | ❌ | ❌ | ✅ | -| Rate limiting (no Redis) | ❌ | ❌ | ❌ | ✅ Planned | - -### Real-World Validation - -From HANDOVER_SANCTIFY.md: - -**Critical Finding**: wp-sinople-theme was using `addslashes()` for RDF Turtle escaping - this is SQL escaping, NOT Turtle escaping. This was a **real RDF injection vulnerability**. - -```php -// BEFORE (vulnerable) -$turtle = '"' . addslashes($label) . '"@en'; // WRONG! SQL escaping ≠ Turtle escaping - -// AFTER (fixed with php-aegis) -use PhpAegis\TurtleEscaper; -$turtle = TurtleEscaper::literal($label, language: 'en'); // ✅ Correct W3C-compliant escaping -``` - -**This validates TurtleEscaper as the #1 unique value proposition.** - ---- - -## Integration with sanctify-php - -php-aegis (runtime protection) and sanctify-php (static analysis) are complementary: - -| Tool | Role | When Used | -|------|------|-----------| -| **sanctify-php** | Static analysis | During development/CI (finds the bugs) | -| **php-aegis** | Runtime security | During request handling (provides the fixes) | - -### Synergy: Safe Sink Recognition - -**sanctify-php should recognize php-aegis methods as "safe sinks"** in taint analysis to reduce false positives: - -```haskell --- sanctify-php taint rules (recommended) -safeSinks = [ - "PhpAegis\\Sanitizer::html", - "PhpAegis\\Sanitizer::attr", - "PhpAegis\\Sanitizer::js", - "PhpAegis\\Sanitizer::css", - "PhpAegis\\Sanitizer::url", - "PhpAegis\\TurtleEscaper::string", - "PhpAegis\\TurtleEscaper::iri", - "PhpAegis\\TurtleEscaper::literal" -] -``` - -### Coordinated Workflow - -``` -┌─────────────────────────────────────────────────────────┐ -│ Development Workflow │ -├─────────────────────────────────────────────────────────┤ -│ │ -│ ┌────────────┐ ┌──────────────┐ ┌──────────────┐ │ -│ │ Write │──▶│ sanctify-php │──▶│ Fix with │ │ -│ │ Code │ │ (finds issues)│ │ php-aegis │ │ -│ └────────────┘ └──────────────┘ └──────────────┘ │ -│ │ │ │ -│ ▼ ▼ │ -│ ┌─────────────────────────────────┐ │ -│ │ sanctify-php recognizes │ │ -│ │ php-aegis as safe, reducing │ │ -│ │ false positives │ │ -│ └─────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────┘ -``` - ---- - -## Development Roadmap Summary - -**Path to 95% (Production Ready)**: - -| Phase | Completion | Description | -|-------|------------|-------------| -| **Phase 1: WordPress Integration** | 65% → 72% | Adapter functions, MU-plugin, tests, guide | -| **Phase 2: IndieWeb Security** | 72% → 78% | Micropub, IndieAuth, Webmention validators | -| **Phase 3: Rate Limiting** | 78% → 83% | Token bucket, file/memory stores | -| **Phase 4: Documentation** | 83% → 90% | API reference, user guide, integration guides | -| **Phase 5: Real-World Validation** | 90% → 95% | Test with 3 themes + 3 plugins, create report | -| **Phase 6: Deployment** | 95% → 100% | Packagist, Docker, GitHub Action | - -**See PHP_AEGIS_DEVELOPMENT_PLAN.md for detailed implementation steps.** - ---- - -## Comparison with sanctify-php Journey - -Both projects followed similar paths to production readiness: - -| Metric | sanctify-php | php-aegis | -|--------|--------------|-----------| -| **Starting Point** | 40% | 65% | -| **Target** | 95% | 95% | -| **Gain Needed** | 55 points | 30 points | -| **Key Milestone** | Parser completion | WordPress integration | -| **Unique Feature** | WordPress-native analysis | RDF/Turtle escaping | -| **Test Suite** | Comprehensive (Hspec) | Comprehensive (PHPUnit) | -| **Documentation** | 60+ pages | Target: 200+ pages | -| **Real-World Validation** | WordPress plugins | Pending | - ---- - -## Immediate Next Steps - -### Priority 1: WordPress Integration (High Impact) -1. Implement adapter functions in `src/WordPress/Adapter.php` -2. Create MU-plugin template in `docs/wordpress/aegis-mu-plugin.php` -3. Write WordPress integration tests in `tests/WordPress/AdapterTest.php` -4. Create comprehensive WordPress guide in `docs/wordpress/WORDPRESS_INTEGRATION.md` -5. Test with 2 real WordPress themes/plugins - -**Why First**: WordPress is the largest PHP ecosystem and primary target audience - -### Priority 2: Publish to Packagist (Highest Impact) -1. Register on packagist.org -2. Configure GitHub webhook -3. Tag version 0.2.0 release -4. Update README with installation instructions -5. Announce on PHP communities - -**Why Second**: Blocks ALL adoption - must be installable - -### Priority 3: Complete Documentation (Medium Impact) -1. Write API reference (100 pages) -2. Write user guide (50 pages) -3. Enhance security guide (OWASP examples) -4. Create integration examples - -**Why Third**: Users can figure out API from tests, but docs improve adoption - ---- - -## Success Criteria for Production Ready (95%) - -### Code Quality -- [ ] 100% test coverage for core functionality -- [ ] PHPStan level 9 (strict) -- [ ] PHP-CS-Fixer (PSR-12) -- [ ] Zero critical security issues - -### Documentation -- [ ] 200+ pages of comprehensive docs -- [ ] 50+ working code examples -- [ ] 3+ framework integration guides -- [ ] 10+ real-world use cases - -### Deployment -- [ ] Published on Packagist -- [ ] Docker image on GHCR -- [ ] GitHub Action for CI integration -- [ ] Pre-built binaries (N/A for PHP) - -### Validation -- [ ] Tested with 3 WordPress themes -- [ ] Tested with 3 WordPress plugins -- [ ] Zero false positives in real code -- [ ] Test report documenting findings - -### Adoption Metrics -- [ ] 100+ Packagist installs/month -- [ ] 50+ GitHub stars -- [ ] 10+ contributors -- [ ] 5+ integration examples in the wild - ---- - -## Related Projects - -| Project | Relationship | Status | -|---------|--------------|--------| -| **sanctify-php** | Static analysis (finds bugs) | 95% complete (production-ready) | -| **indieweb2-bastion** | Infrastructure security | 70% complete (GraphQL DNS pending) | -| **wp-audit-toolkit** | WordPress auditing | Unknown | -| **proof-of-work** | Spam prevention | Production | - ---- - -## Key Learnings from sanctify-php - -Applying lessons from sanctify-php's journey to 95%: - -1. **Real-world validation is critical** - Test against actual WordPress plugins/themes -2. **Documentation matters** - 60+ pages made sanctify-php production-ready -3. **Test coverage is non-negotiable** - Comprehensive test suite builds confidence -4. **Unique features win** - TurtleEscaper is to php-aegis what WordPress-native analysis is to sanctify-php -5. **Publish early** - Don't wait for 100% - publish at 95% - ---- - -## Conclusion - -php-aegis has a **solid foundation at 65% with unique capabilities** (RDF/Turtle escaping that fixed real vulnerabilities). With focused effort on WordPress integration, documentation, and publishing, it can reach **95% production-ready status** and serve as the runtime complement to sanctify-php's static analysis. - -**The TurtleEscaper feature alone justifies php-aegis's existence** - it's the only PHP library that properly handles RDF Turtle escaping, as validated by fixing a real critical vulnerability in wp-sinople-theme. - -**Recommended approach**: Follow the same comprehensive methodology used for sanctify-php: -1. Complete core functionality (WordPress, IndieWeb, rate limiting) -2. Comprehensive documentation (200+ pages) -3. Real-world validation (test against actual WordPress code) -4. Professional deployment (Packagist, Docker, GitHub Action) - -**Timeline Philosophy**: Per project guidelines, no time estimates provided. Work proceeds based on: -- User demand (GitHub issues) -- Security criticality -- Contributor availability - ---- - -*Analysis completed 2026-01-22. Ready to proceed with Phase 1: WordPress Integration.* diff --git a/PHP_AEGIS_DEVELOPMENT_PLAN.md b/PHP_AEGIS_DEVELOPMENT_PLAN.adoc similarity index 55% rename from PHP_AEGIS_DEVELOPMENT_PLAN.md rename to PHP_AEGIS_DEVELOPMENT_PLAN.adoc index 03f36f6..e7374e6 100644 --- a/PHP_AEGIS_DEVELOPMENT_PLAN.md +++ b/PHP_AEGIS_DEVELOPMENT_PLAN.adoc @@ -1,65 +1,66 @@ -# php-aegis Development Plan -**Created**: 2026-01-22 -**Project Phase**: Active Development -**Current Completion**: 65% -**Target Completion**: 95% (Production Ready) +== php-aegis Development Plan ---- +*Created*: 2026-01-22 *Project Phase*: Active Development *Current +Completion*: 65% *Target Completion*: 95% (Production Ready) + +''''' -## Executive Summary +=== Executive Summary -php-aegis is a PHP 8.1+ security and hardening toolkit providing input validation, sanitization, and security utilities. This plan outlines the path from 65% to 95%+ completion with production-ready status. +php-aegis is a PHP 8.1+ security and hardening toolkit providing input +validation, sanitization, and security utilities. This plan outlines the +path from 65% to 95%+ completion with production-ready status. -### Current State +==== Current State -**Working Features** (65% complete): -- ✅ Validator class (17 methods): email, URL, IP, UUID, slug, JSON, filename safety, semver, ISO 8601, hex colors -- ✅ Sanitizer class (10 methods): HTML, JS, CSS, URL, JSON, stripTags, filename, removeNullBytes -- ✅ **TurtleEscaper class** (UNIQUE VALUE): W3C-compliant RDF Turtle escaping - no other PHP library does this -- ✅ Headers class: CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy -- ✅ Crypto utilities: Cryptographic functions and secure random generation -- ✅ Comprehensive test suite: 4 test files (67KB), PHPUnit configured -- ✅ Static methods throughout (no instance state needed) -- ✅ SPDX license headers on all files -- ✅ Composer package (MIT license, PHP 8.1+ requirement) +*Working Features* (65% complete): - ✅ Validator class (17 methods): +email, URL, IP, UUID, slug, JSON, filename safety, semver, ISO 8601, hex +colors - ✅ Sanitizer class (10 methods): HTML, JS, CSS, URL, JSON, +stripTags, filename, removeNullBytes - ✅ *TurtleEscaper class* (UNIQUE +VALUE): W3C-compliant RDF Turtle escaping - no other PHP library does +this - ✅ Headers class: CSP, HSTS, X-Frame-Options, Referrer-Policy, +Permissions-Policy - ✅ Crypto utilities: Cryptographic functions and +secure random generation - ✅ Comprehensive test suite: 4 test files +(67KB), PHPUnit configured - ✅ Static methods throughout (no instance +state needed) - ✅ SPDX license headers on all files - ✅ Composer +package (MIT license, PHP 8.1+ requirement) -**Code Metrics**: -- Total lines: 3,173 -- Source files: 5 (Validator.php, Sanitizer.php, Headers.php, TurtleEscaper.php, Crypto.php) -- Test files: 4 (ValidatorTest.php, SanitizerTest.php, HeadersTest.php, TurtleEscaperTest.php) -- Dependencies: zero runtime dependencies +*Code Metrics*: - Total lines: 3,173 - Source files: 5 (Validator.php, +Sanitizer.php, Headers.php, TurtleEscaper.php, Crypto.php) - Test files: +4 (ValidatorTest.php, SanitizerTest.php, HeadersTest.php, +TurtleEscaperTest.php) - Dependencies: zero runtime dependencies -### Gap Analysis +==== Gap Analysis -**Critical Blockers** (Medium Priority): -1. WordPress integration (0%) - Adapter functions, mu-plugin pattern -2. sanctify-php coordination (0%) - Safe sink recognition -3. Packagist publication (0%) - Not published yet +*Critical Blockers* (Medium Priority): 1. WordPress integration (0%) - +Adapter functions, mu-plugin pattern 2. sanctify-php coordination (0%) - +Safe sink recognition 3. Packagist publication (0%) - Not published yet 4. Real-world validation (0%) - No test integrations -**Feature Gaps**: -1. IndieWeb security (0%) - Micropub, IndieAuth, Webmention validators -2. Rate limiting (0%) - Token bucket implementation -3. Framework adapters (0%) - Laravel service provider, Symfony bundle +*Feature Gaps*: 1. IndieWeb security (0%) - Micropub, IndieAuth, +Webmention validators 2. Rate limiting (0%) - Token bucket +implementation 3. Framework adapters (0%) - Laravel service provider, +Symfony bundle -**Documentation Gaps** (30% complete): -1. API reference incomplete -2. WordPress integration guide missing -3. IndieWeb examples missing -4. Deployment guide incomplete +*Documentation Gaps* (30% complete): 1. API reference incomplete 2. +WordPress integration guide missing 3. IndieWeb examples missing 4. +Deployment guide incomplete ---- +''''' -## Development Roadmap (65% → 95%) +=== Development Roadmap (65% → 95%) -### Phase 1: WordPress Integration (65% → 72%) +==== Phase 1: WordPress Integration (65% → 72%) -**Goal**: Enable seamless WordPress integration with wrapper functions and best practices guide. +*Goal*: Enable seamless WordPress integration with wrapper functions and +best practices guide. -#### 1.1 WordPress Adapter Functions -Create `src/WordPress/Adapter.php`: +===== 1.1 WordPress Adapter Functions -```php +Create `+src/WordPress/Adapter.php+`: + +[source,php] +---- assertStringContainsString('"Hello \\"World\\""@en', $output); } } -``` +---- -#### 1.4 WordPress Documentation -Create `docs/wordpress/WORDPRESS_INTEGRATION.md`: +===== 1.4 WordPress Documentation -```markdown +Create `+docs/wordpress/WORDPRESS_INTEGRATION.md+`: + +[source,markdown] +---- # WordPress Integration Guide ## Installation @@ -211,23 +218,28 @@ Create `docs/wordpress/WORDPRESS_INTEGRATION.md`: ```bash cd wp-content/mu-plugins composer require hyperpolymath/php-aegis -``` +---- -### Method 2: Manual Installation -Download and place in `wp-content/mu-plugins/php-aegis/` +==== Method 2: Manual Installation -## Usage in Themes +Download and place in `+wp-content/mu-plugins/php-aegis/+` -### Basic Sanitization -```php +=== Usage in Themes + +==== Basic Sanitization + +[source,php] +---- -``` +---- -### RDF/Turtle Output (Unique Feature!) -```php +==== RDF/Turtle Output (Unique Feature!) + +[source,php] +---- input('resource_id'); +if (!Validator::uuid($uuid)) { + abort(400, 'Invalid resource ID'); +} + +// DO: Use for security headers (Laravel's is less comprehensive) +Headers::secure(); +---- + +==== For Vanilla PHP / APIs + +[source,php] +---- +// DO: Use php-aegis as your primary security layer +use PhpAegis\{Validator, Sanitizer, Headers}; + +// Apply security headers +Headers::secure(); + +// Validate input +if (!Validator::email($_POST['email'])) { + http_response_code(400); + exit(json_encode(['error' => 'Invalid email'])); +} + +// Sanitize output +echo Sanitizer::html($userContent); +---- + +''''' + +=== Marketing Positioning + +==== Tagline Options + +[arabic] +. *"`Security for the rest of PHP`"* - Emphasizes non-framework use +. *"`Where frameworks fear to tread`"* - Emphasizes unique capabilities +. *"`Semantic web security, done right`"* - Emphasizes Turtle escaping +niche + +==== README Messaging + +.... +php-aegis is a zero-dependency PHP security toolkit for: +- API services without view layers +- CLI tools and microservices +- Semantic web applications (RDF/Turtle) +- Any PHP app without a framework + +For WordPress, use WordPress core functions. +For Laravel/Symfony, use framework helpers + aegis for gaps. +.... + +''''' + +=== Roadmap Implications + +Based on this positioning, prioritize: + +[arabic] +. *RDF/Turtle escaping* - Already done, unique differentiator +. *Security headers* - Already done, fills framework gaps +. *Extended validators* - Focus on what WordPress lacks (UUID, IP, +semver, etc.) +. *IndieWeb security* - Micropub, IndieAuth, Webmention (unique niche) +. *Rate limiting* - File-based, no Redis required + +De-prioritize: - HTML/attribute escaping improvements (frameworks do +this well) - WordPress adapter (WordPress users should use WordPress +functions) + +''''' + +=== Success Metrics + +[cols=",",options="header",] +|=== +|Metric |Target Audience Indicator +|Downloads from API/microservice projects |Primary audience +|Usage in semantic web tools |Niche but high-value +|Issues asking about WordPress |Signals need for better docs +|PRs adding framework adapters |Community wants integration +|=== + +''''' + +_This positioning reflects insights from WordPress theme +(wp-sinople-theme) and plugin (Zotpress) integration attempts._ diff --git a/POSITIONING.md b/POSITIONING.md deleted file mode 100644 index 4a35c85..0000000 --- a/POSITIONING.md +++ /dev/null @@ -1,231 +0,0 @@ -# php-aegis Positioning & Target Audience - -## The Problem We Discovered - -After integrating php-aegis with multiple WordPress projects (themes and plugins), we found: - -> **WordPress already has comprehensive security APIs** (`esc_html()`, `esc_attr()`, `wp_kses()`, etc.) that are deeply integrated with the WordPress ecosystem. - -This means php-aegis **should not compete** with WordPress core functions. Instead, it should: - -1. **Target non-WordPress PHP applications** where no security API exists -2. **Provide unique capabilities** that WordPress (and other frameworks) lack - ---- - -## Target Audience Matrix - -| Audience | php-aegis Value | Recommendation | -|----------|-----------------|----------------| -| **WordPress plugins/themes** | Low | Use WordPress core functions | -| **Laravel applications** | Medium | Use Laravel's helpers, aegis for gaps | -| **Symfony applications** | Medium | Use Twig's escaping, aegis for gaps | -| **Vanilla PHP applications** | **High** | php-aegis is the primary security layer | -| **API-only services** | **High** | No view layer = no framework escaping | -| **CLI tools** | **High** | No framework = aegis fills the gap | -| **Microservices** | **High** | Lightweight, zero-dependency | -| **Semantic Web apps** | **Very High** | TurtleEscaper is unique | - ---- - -## What WordPress Has (Don't Duplicate) - -| WordPress Function | Purpose | php-aegis Equivalent | -|--------------------|---------|---------------------| -| `esc_html()` | HTML content escaping | `Sanitizer::html()` | -| `esc_attr()` | HTML attribute escaping | `Sanitizer::attr()` | -| `esc_url()` | URL escaping with protocol check | `Sanitizer::url()` | -| `esc_js()` | JavaScript escaping | `Sanitizer::js()` | -| `wp_kses()` | HTML filtering with allowlist | ❌ Not implemented | -| `wp_kses_post()` | HTML filtering for posts | ❌ Not implemented | -| `sanitize_text_field()` | Text sanitization | `Sanitizer::stripTags()` | -| `is_email()` | Email validation | `Validator::email()` | -| `wp_http_validate_url()` | URL validation + SSL | `Validator::url()` | -| `absint()` | Positive integer | `Validator::int(..., min: 0)` | - -**For WordPress projects**: Use WordPress functions. They're more battle-tested, ecosystem-integrated, and maintained by Automattic. - ---- - -## What php-aegis Provides (Unique Value) - -These capabilities are **not available** in WordPress, Laravel, or Symfony: - -### 1. RDF/Turtle Escaping (Unique) - -No other PHP library provides W3C-compliant Turtle escaping. - -```php -use PhpAegis\TurtleEscaper; - -// Safe for semantic web applications -TurtleEscaper::string($userLabel); -TurtleEscaper::iri($userProvidedUri); -TurtleEscaper::triple($subject, $predicate, $object, 'en'); -``` - -**Use cases**: -- Linked Data platforms -- Knowledge graphs -- Semantic WordPress themes (like wp-sinople-theme) -- SPARQL endpoint integrations - -### 2. Security Headers Helper - -WordPress doesn't provide header helpers. Frameworks have partial support. - -```php -use PhpAegis\Headers; - -// One-line security hardening -Headers::secure(); - -// Or fine-grained control -Headers::contentSecurityPolicy([...]); -Headers::strictTransportSecurity(maxAge: 31536000, preload: true); -Headers::permissionsPolicy([...]); -``` - -### 3. Extended Validators Not in WordPress - -| php-aegis | WordPress Equivalent | Notes | -|-----------|---------------------|-------| -| `Validator::uuid()` | ❌ None | RFC 4122 UUID validation | -| `Validator::ip()` | ❌ None | IPv4/IPv6 validation | -| `Validator::ipv4()` | ❌ None | IPv4 only | -| `Validator::ipv6()` | ❌ None | IPv6 only | -| `Validator::domain()` | ❌ None | RFC 1035 domain validation | -| `Validator::hostname()` | ❌ None | Domain or IP | -| `Validator::slug()` | `sanitize_title()` | WP sanitizes, aegis validates | -| `Validator::semver()` | ❌ None | Semantic versioning | -| `Validator::iso8601()` | ❌ None | ISO 8601 datetime | -| `Validator::hexColor()` | `sanitize_hex_color()` | WP sanitizes, aegis validates | -| `Validator::safeFilename()` | `sanitize_file_name()` | WP sanitizes, aegis validates | -| `Validator::json()` | ❌ None | JSON structure validation | -| `Validator::int(min, max)` | ❌ None | Integer with range | -| `Validator::printable()` | ❌ None | ASCII printable only | -| `Validator::noNullBytes()` | ❌ None | Path traversal prevention | -| `Validator::httpsUrl()` | `wp_http_validate_url()` | WP has `$ssl` param | - -### 4. Zero Dependencies - -- WordPress functions require WordPress -- Laravel helpers require Laravel -- Symfony components require Symfony - -php-aegis works in any PHP 8.1+ environment with no dependencies. - ---- - -## Recommended Usage Patterns - -### For WordPress Projects - -```php -// DON'T: Use php-aegis for basic escaping -echo \PhpAegis\Sanitizer::html($content); // ❌ Redundant - -// DO: Use WordPress functions -echo esc_html($content); // ✅ Preferred - -// DO: Use php-aegis for unique capabilities -$headers = new \PhpAegis\Headers(); -$headers::secure(); // ✅ WordPress lacks this - -// DO: Use php-aegis for semantic web features -echo \PhpAegis\TurtleEscaper::string($label); // ✅ WordPress lacks this - -// DO: Use php-aegis for validation gaps -if (!\PhpAegis\Validator::uuid($_GET['id'])) { // ✅ WordPress lacks this - wp_die('Invalid ID'); -} -``` - -### For Laravel Projects - -```php -// DON'T: Use php-aegis for Blade escaping -{{ $content }} // Blade auto-escapes, don't use aegis - -// DO: Use php-aegis in non-Blade contexts -$uuid = $request->input('resource_id'); -if (!Validator::uuid($uuid)) { - abort(400, 'Invalid resource ID'); -} - -// DO: Use for security headers (Laravel's is less comprehensive) -Headers::secure(); -``` - -### For Vanilla PHP / APIs - -```php -// DO: Use php-aegis as your primary security layer -use PhpAegis\{Validator, Sanitizer, Headers}; - -// Apply security headers -Headers::secure(); - -// Validate input -if (!Validator::email($_POST['email'])) { - http_response_code(400); - exit(json_encode(['error' => 'Invalid email'])); -} - -// Sanitize output -echo Sanitizer::html($userContent); -``` - ---- - -## Marketing Positioning - -### Tagline Options - -1. **"Security for the rest of PHP"** - Emphasizes non-framework use -2. **"Where frameworks fear to tread"** - Emphasizes unique capabilities -3. **"Semantic web security, done right"** - Emphasizes Turtle escaping niche - -### README Messaging - -``` -php-aegis is a zero-dependency PHP security toolkit for: -- API services without view layers -- CLI tools and microservices -- Semantic web applications (RDF/Turtle) -- Any PHP app without a framework - -For WordPress, use WordPress core functions. -For Laravel/Symfony, use framework helpers + aegis for gaps. -``` - ---- - -## Roadmap Implications - -Based on this positioning, prioritize: - -1. **RDF/Turtle escaping** - Already done, unique differentiator -2. **Security headers** - Already done, fills framework gaps -3. **Extended validators** - Focus on what WordPress lacks (UUID, IP, semver, etc.) -4. **IndieWeb security** - Micropub, IndieAuth, Webmention (unique niche) -5. **Rate limiting** - File-based, no Redis required - -De-prioritize: -- HTML/attribute escaping improvements (frameworks do this well) -- WordPress adapter (WordPress users should use WordPress functions) - ---- - -## Success Metrics - -| Metric | Target Audience Indicator | -|--------|--------------------------| -| Downloads from API/microservice projects | Primary audience | -| Usage in semantic web tools | Niche but high-value | -| Issues asking about WordPress | Signals need for better docs | -| PRs adding framework adapters | Community wants integration | - ---- - -*This positioning reflects insights from WordPress theme (wp-sinople-theme) and plugin (Zotpress) integration attempts.* diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc new file mode 100644 index 0000000..27f45f0 --- /dev/null +++ b/PROOF-NEEDS.adoc @@ -0,0 +1,39 @@ +== PROOF-NEEDS.md — php-aegis + +=== Current State + +* **src/abi/*.idr**: NO +* *Dangerous patterns*: 0 +* *LOC*: ~10,200 (PHP) +* *ABI layer*: Missing + +=== What Needs Proving + +[width="100%",cols="51%,27%,22%",options="header",] +|=== +|Component |What |Why +|Security header generation |Generated headers are well-formed and +complete |Malformed security headers leave sites unprotected + +|CSP policy construction |Content Security Policy prevents all XSS +vectors |Incomplete CSP allows cross-site scripting + +|Webmention validation |IndieWeb Webmention verification is correct +|Spoofed webmentions inject malicious content + +|Input validation |All validators reject malicious input |Validator +bypass is a security vulnerability +|=== + +=== Recommended Prover + +*Idris2* — Create `+src/abi/+` with security header correctness types. +CSP policy completeness is a natural fit for exhaustive pattern +matching. PHP code would need a separate verification approach +(potentially PHPStan + custom rules). + +=== Priority + +*MEDIUM* — Security library deployed on production websites (lcb-website +uses it). Incorrect security headers directly expose users to attacks. +CSP completeness is the highest-value proof target. diff --git a/PROOF-NEEDS.md b/PROOF-NEEDS.md deleted file mode 100644 index 1ead99e..0000000 --- a/PROOF-NEEDS.md +++ /dev/null @@ -1,25 +0,0 @@ -# PROOF-NEEDS.md — php-aegis - -## Current State - -- **src/abi/*.idr**: NO -- **Dangerous patterns**: 0 -- **LOC**: ~10,200 (PHP) -- **ABI layer**: Missing - -## What Needs Proving - -| Component | What | Why | -|-----------|------|-----| -| Security header generation | Generated headers are well-formed and complete | Malformed security headers leave sites unprotected | -| CSP policy construction | Content Security Policy prevents all XSS vectors | Incomplete CSP allows cross-site scripting | -| Webmention validation | IndieWeb Webmention verification is correct | Spoofed webmentions inject malicious content | -| Input validation | All validators reject malicious input | Validator bypass is a security vulnerability | - -## Recommended Prover - -**Idris2** — Create `src/abi/` with security header correctness types. CSP policy completeness is a natural fit for exhaustive pattern matching. PHP code would need a separate verification approach (potentially PHPStan + custom rules). - -## Priority - -**MEDIUM** — Security library deployed on production websites (lcb-website uses it). Incorrect security headers directly expose users to attacks. CSP completeness is the highest-value proof target. diff --git a/ROADMAP_PRIORITY.adoc b/ROADMAP_PRIORITY.adoc new file mode 100644 index 0000000..5c8eff2 --- /dev/null +++ b/ROADMAP_PRIORITY.adoc @@ -0,0 +1,386 @@ +== php-aegis Roadmap (Integration-Informed Priority) + +This roadmap is prioritized based on real-world integration experience +with WordPress themes and plugins, reflecting lessons from +wp-sinople-theme and Zotpress integrations. + +=== Strategic Positioning + +See POSITIONING.md for full positioning strategy. + +*Key insight*: WordPress (and Laravel, Symfony) already have +comprehensive security APIs. php-aegis should: + +[arabic] +. *Target non-framework PHP* - APIs, CLI tools, microservices +. *Provide unique capabilities* - RDF/Turtle, security headers, extended +validators +. *Fill framework gaps* - What WordPress/Laravel/Symfony don’t provide + +*Do NOT prioritize*: Duplicating `+esc_html()+`, `+esc_attr()+` +equivalents that frameworks already do well. + +=== Context: Integration Findings + +[width="100%",cols="60%,40%",options="header",] +|=== +|Integration |Finding +|wp-sinople-theme |RDF/Turtle escaping is unique value; basic +sanitization duplicates WordPress + +|Zotpress plugin |Mature WP plugins already use core functions; +php-aegis not needed for basic security +|=== + +*Prioritize features WordPress lacks*: - RDF/Turtle escaping ✅ - +Security headers ✅ - Extended validators (UUID, IP, semver, etc.) ✅ - +IndieWeb security (Micropub, IndieAuth) - Rate limiting without external +dependencies + +''''' + +=== Phase 1: Foundation Fixes (v0.1.1) + +*Goal*: Address compliance and differentiation issues immediately. + +==== 1.1 SPDX License Headers ✅ + +* Add `+SPDX-License-Identifier: CC-BY-SA-4.0 OR PMPL-1.0-or-later+` to +all PHP files +* Add `+SPDX-FileCopyrightText+` with year and author + +==== 1.2 Static Methods + +* Convert `+Validator+` and `+Sanitizer+` to use static methods +* Rationale: No instance state needed, improves ergonomics +* Before: `+(new Sanitizer())->html($input)+` +* After: `+Sanitizer::html($input)+` + +==== 1.3 RDF/Turtle Escaping Module ✅ + +* `+TurtleEscaper::string(string $input): string+` - Escape for Turtle +string literals +* `+TurtleEscaper::iri(string $uri): string+` - Escape/validate for +Turtle IRIs +* This is a *unique differentiator* - no other PHP library does this +properly + +''''' + +=== Phase 2: Security Headers (v0.2.0) + +*Goal*: Provide value beyond WordPress built-ins. + +==== 2.1 Headers Class + +[source,php] +---- +Headers::contentSecurityPolicy(array $directives): void +Headers::strictTransportSecurity(int $maxAge, bool $subdomains = true): void +Headers::xFrameOptions(string $value = 'DENY'): void +Headers::xContentTypeOptions(): void // nosniff +Headers::referrerPolicy(string $policy = 'strict-origin-when-cross-origin'): void +Headers::permissionsPolicy(array $permissions): void +---- + +==== 2.2 All-in-One Security Headers + +[source,php] +---- +Headers::secure(): void // Apply sensible defaults for all headers +---- + +==== Why This Matters + +* WordPress doesn’t provide header helpers +* Frameworks often require manual configuration +* This provides "`secure by default`" with one function call + +''''' + +=== Phase 3: Extended Validators (v0.3.0) + +*Goal*: Cover common validation needs with strict, type-safe +implementations. + +==== 3.1 Network Validators + +[source,php] +---- +Validator::ip(string $ip): bool // IPv4 or IPv6 +Validator::ipv4(string $ip): bool +Validator::ipv6(string $ip): bool +Validator::cidr(string $cidr): bool +Validator::hostname(string $host): bool +Validator::domain(string $domain): bool +---- + +==== 3.2 Format Validators + +[source,php] +---- +Validator::uuid(string $uuid): bool // RFC 4122 +Validator::slug(string $slug): bool // URL-safe slugs +Validator::semver(string $version): bool // Semantic versioning +Validator::iso8601(string $date): bool // ISO 8601 datetime +Validator::json(string $json): bool // Valid JSON +---- + +==== 3.3 Security Validators + +[source,php] +---- +Validator::noNullBytes(string $input): bool +Validator::printable(string $input): bool +Validator::safeFilename(string $filename): bool // No path traversal +Validator::httpsUrl(string $url): bool // Enforce HTTPS +---- + +''''' + +=== Phase 4: Context-Aware Sanitization (v0.4.0) + +*Goal*: Provide correct escaping for every output context. + +==== 4.1 Context Enum (PHP 8.1+) + +[source,php] +---- +enum OutputContext: string { + case Html = 'html'; + case HtmlAttribute = 'attr'; + case JavaScript = 'js'; + case Css = 'css'; + case Url = 'url'; + case Sql = 'sql'; // For display only, not query building + case Json = 'json'; + case Turtle = 'turtle'; // RDF Turtle + case NTriples = 'ntriples'; // RDF N-Triples +} +---- + +==== 4.2 Unified Escape Method + +[source,php] +---- +Sanitizer::escape(string $input, OutputContext $context): string +---- + +==== 4.3 Specialized Methods + +[source,php] +---- +Sanitizer::jsString(string $input): string // Safe for JS string literals +Sanitizer::cssString(string $input): string // Safe for CSS values +Sanitizer::urlEncode(string $input): string // Proper URL encoding +Sanitizer::jsonEncode(mixed $input): string // Safe JSON with flags +---- + +''''' + +=== Phase 5: IndieWeb Security (v0.5.0) + +*Goal*: First-class support for IndieWeb/semantic web patterns. + +==== Related Project: indieweb2-bastion + +The +https://github.com/hyperpolymath/indieweb2-bastion[indieweb2-bastion] +repository provides infrastructure-layer security (bastion ingress, +oblivious DNS, provenance graphs) that complements php-aegis at the +application layer. + +*Architectural relationship*: + +.... +┌────────────────────────────────────────────────┐ +│ indieweb2-bastion │ Infrastructure layer │ +│ (network, audit) │ Rate limiting, logging │ +├─────────────────────┼──────────────────────────┤ +│ php-aegis │ Application layer │ +│ (this module) │ Micropub, IndieAuth, │ +│ │ Webmention validation │ +└────────────────────────────────────────────────┘ +.... + +*Lessons from indieweb2-bastion*: - Use provenance-style tracking for +Webmention verification chains - Apply bastion patterns for rate +limiting endpoints - Consider audit logging as a first-class feature + +==== 5.1 Micropub Content Sanitizer + +[source,php] +---- +Micropub::sanitizeContent(string $html, array $allowedTags = []): string +Micropub::validateEntry(array $mf2): ValidationResult +---- + +==== 5.2 IndieAuth Helpers + +[source,php] +---- +IndieAuth::verifyToken(string $token, string $endpoint): TokenResult +IndieAuth::validateMe(string $url): bool // Valid "me" URL +IndieAuth::validateRedirectUri(string $uri, string $clientId): bool +---- + +==== 5.3 Webmention Validators + +[source,php] +---- +Webmention::validateSource(string $url): bool // Not internal IP +Webmention::validateTarget(string $url, string $domain): bool +---- + +==== 5.4 SSRF Prevention + +[source,php] +---- +// Prevent Webmention SSRF attacks +Webmention::isInternalIp(string $ip): bool +Webmention::resolveAndValidate(string $url): ValidationResult +---- + +''''' + +=== Phase 6: Rate Limiting (v0.6.0) + +*Goal*: Protect against abuse without external dependencies. + +==== 6.1 Token Bucket Implementation + +[source,php] +---- +interface RateLimitStore { + public function get(string $key): ?TokenBucket; + public function set(string $key, TokenBucket $bucket, int $ttl): void; +} + +class MemoryStore implements RateLimitStore { ... } +class FileStore implements RateLimitStore { ... } +class RedisStore implements RateLimitStore { ... } // Optional +class ApcuStore implements RateLimitStore { ... } // Optional +---- + +==== 6.2 Rate Limiter + +[source,php] +---- +$limiter = new RateLimiter( + store: new FileStore('/tmp/ratelimit'), + capacity: 100, // requests + refillRate: 10, // per second +); + +if (!$limiter->attempt($clientIp)) { + http_response_code(429); + exit; +} +---- + +''''' + +=== Phase 7: Ecosystem Expansion (v0.7.0) + +*Goal*: Maximize adoption across PHP ecosystem. + +==== 7.1 Compatibility Package + +Create `+hyperpolymath/php-aegis-compat+` for PHP 7.4+ environments. + +See COMPATIBILITY.md for full strategy. + +[source,bash] +---- +# PHP 7.4+ (legacy WordPress hosts) +composer require hyperpolymath/php-aegis-compat + +# PHP 8.1+ (recommended) +composer require hyperpolymath/php-aegis +---- + +==== 7.2 WordPress Adapter + +WordPress-style function wrappers: + +[source,php] +---- +aegis_html($input) // Maps to Sanitizer::html() +aegis_attr($input) // Maps to Sanitizer::attr() +aegis_js($input) // Maps to Sanitizer::js() +aegis_url($input) // Maps to Sanitizer::url() +aegis_send_security_headers() // Maps to Headers::secure() +---- + +==== 7.3 Laravel Service Provider + +[source,php] +---- +// Auto-registered via package discovery +PhpAegis\Laravel\AegisServiceProvider::class + +// Blade directive +@aegis($userContent) + +// DI in controllers +public function store(Sanitizer $sanitizer) { ... } +---- + +==== 7.4 Symfony Bundle + +[source,php] +---- +// config/bundles.php +PhpAegis\Symfony\AegisBundle::class => ['all' => true] + +// Twig filter +{{ user_content|aegis_html }} +---- + +''''' + +=== Differentiation Strategy + +==== What WordPress Has (don’t duplicate) + +* `+esc_html()+`, `+esc_attr()+`, `+esc_url()+`, `+esc_js()+` +* `+wp_kses()+`, `+wp_kses_post()+` +* `+sanitize_*()+` functions +* Nonce verification + +==== What php-aegis Provides (unique value) + +[cols=",,,,",options="header",] +|=== +|Feature |WordPress |Laravel |Symfony |php-aegis +|RDF/Turtle escaping |❌ |❌ |❌ |✅ +|Security headers helper |❌ |Partial |Partial |✅ +|IndieWeb validation |❌ |❌ |❌ |✅ +|Zero dependencies |N/A |❌ |❌ |✅ +|PHP 8.1+ strict types |❌ |❌ |❌ |✅ +|Rate limiting (no Redis) |❌ |❌ |❌ |✅ +|=== + +''''' + +=== Success Metrics + +[arabic] +. *Adoption*: Downloads on Packagist +. *Integration*: Used in WordPress themes, Laravel packages +. *Coverage*: CVE fixes attributable to php-aegis usage +. *Community*: GitHub stars, issues, PRs + +''''' + +=== Timeline Philosophy + +Per project guidelines, no time estimates are provided. Work proceeds +based on: 1. User demand (GitHub issues) 2. Security criticality 3. +Contributor availability + +Phases can be reordered based on community feedback. + +''''' + +_This roadmap reflects lessons learned from real WordPress integration._ diff --git a/ROADMAP_PRIORITY.md b/ROADMAP_PRIORITY.md deleted file mode 100644 index 6cdd4f8..0000000 --- a/ROADMAP_PRIORITY.md +++ /dev/null @@ -1,327 +0,0 @@ -# php-aegis Roadmap (Integration-Informed Priority) - -This roadmap is prioritized based on real-world integration experience with WordPress themes and plugins, reflecting lessons from wp-sinople-theme and Zotpress integrations. - -## Strategic Positioning - -See [POSITIONING.md](POSITIONING.md) for full positioning strategy. - -**Key insight**: WordPress (and Laravel, Symfony) already have comprehensive security APIs. php-aegis should: - -1. **Target non-framework PHP** - APIs, CLI tools, microservices -2. **Provide unique capabilities** - RDF/Turtle, security headers, extended validators -3. **Fill framework gaps** - What WordPress/Laravel/Symfony don't provide - -**Do NOT prioritize**: Duplicating `esc_html()`, `esc_attr()` equivalents that frameworks already do well. - -## Context: Integration Findings - -| Integration | Finding | -|-------------|---------| -| wp-sinople-theme | RDF/Turtle escaping is unique value; basic sanitization duplicates WordPress | -| Zotpress plugin | Mature WP plugins already use core functions; php-aegis not needed for basic security | - -**Prioritize features WordPress lacks**: -- RDF/Turtle escaping ✅ -- Security headers ✅ -- Extended validators (UUID, IP, semver, etc.) ✅ -- IndieWeb security (Micropub, IndieAuth) -- Rate limiting without external dependencies - ---- - -## Phase 1: Foundation Fixes (v0.1.1) - -**Goal**: Address compliance and differentiation issues immediately. - -### 1.1 SPDX License Headers ✅ -- Add `SPDX-License-Identifier: CC-BY-SA-4.0 OR PMPL-1.0-or-later` to all PHP files -- Add `SPDX-FileCopyrightText` with year and author - -### 1.2 Static Methods -- Convert `Validator` and `Sanitizer` to use static methods -- Rationale: No instance state needed, improves ergonomics -- Before: `(new Sanitizer())->html($input)` -- After: `Sanitizer::html($input)` - -### 1.3 RDF/Turtle Escaping Module ✅ -- `TurtleEscaper::string(string $input): string` - Escape for Turtle string literals -- `TurtleEscaper::iri(string $uri): string` - Escape/validate for Turtle IRIs -- This is a **unique differentiator** - no other PHP library does this properly - ---- - -## Phase 2: Security Headers (v0.2.0) - -**Goal**: Provide value beyond WordPress built-ins. - -### 2.1 Headers Class -```php -Headers::contentSecurityPolicy(array $directives): void -Headers::strictTransportSecurity(int $maxAge, bool $subdomains = true): void -Headers::xFrameOptions(string $value = 'DENY'): void -Headers::xContentTypeOptions(): void // nosniff -Headers::referrerPolicy(string $policy = 'strict-origin-when-cross-origin'): void -Headers::permissionsPolicy(array $permissions): void -``` - -### 2.2 All-in-One Security Headers -```php -Headers::secure(): void // Apply sensible defaults for all headers -``` - -### Why This Matters -- WordPress doesn't provide header helpers -- Frameworks often require manual configuration -- This provides "secure by default" with one function call - ---- - -## Phase 3: Extended Validators (v0.3.0) - -**Goal**: Cover common validation needs with strict, type-safe implementations. - -### 3.1 Network Validators -```php -Validator::ip(string $ip): bool // IPv4 or IPv6 -Validator::ipv4(string $ip): bool -Validator::ipv6(string $ip): bool -Validator::cidr(string $cidr): bool -Validator::hostname(string $host): bool -Validator::domain(string $domain): bool -``` - -### 3.2 Format Validators -```php -Validator::uuid(string $uuid): bool // RFC 4122 -Validator::slug(string $slug): bool // URL-safe slugs -Validator::semver(string $version): bool // Semantic versioning -Validator::iso8601(string $date): bool // ISO 8601 datetime -Validator::json(string $json): bool // Valid JSON -``` - -### 3.3 Security Validators -```php -Validator::noNullBytes(string $input): bool -Validator::printable(string $input): bool -Validator::safeFilename(string $filename): bool // No path traversal -Validator::httpsUrl(string $url): bool // Enforce HTTPS -``` - ---- - -## Phase 4: Context-Aware Sanitization (v0.4.0) - -**Goal**: Provide correct escaping for every output context. - -### 4.1 Context Enum (PHP 8.1+) -```php -enum OutputContext: string { - case Html = 'html'; - case HtmlAttribute = 'attr'; - case JavaScript = 'js'; - case Css = 'css'; - case Url = 'url'; - case Sql = 'sql'; // For display only, not query building - case Json = 'json'; - case Turtle = 'turtle'; // RDF Turtle - case NTriples = 'ntriples'; // RDF N-Triples -} -``` - -### 4.2 Unified Escape Method -```php -Sanitizer::escape(string $input, OutputContext $context): string -``` - -### 4.3 Specialized Methods -```php -Sanitizer::jsString(string $input): string // Safe for JS string literals -Sanitizer::cssString(string $input): string // Safe for CSS values -Sanitizer::urlEncode(string $input): string // Proper URL encoding -Sanitizer::jsonEncode(mixed $input): string // Safe JSON with flags -``` - ---- - -## Phase 5: IndieWeb Security (v0.5.0) - -**Goal**: First-class support for IndieWeb/semantic web patterns. - -### Related Project: indieweb2-bastion - -The [indieweb2-bastion](https://github.com/hyperpolymath/indieweb2-bastion) repository provides infrastructure-layer security (bastion ingress, oblivious DNS, provenance graphs) that complements php-aegis at the application layer. - -**Architectural relationship**: -``` -┌────────────────────────────────────────────────┐ -│ indieweb2-bastion │ Infrastructure layer │ -│ (network, audit) │ Rate limiting, logging │ -├─────────────────────┼──────────────────────────┤ -│ php-aegis │ Application layer │ -│ (this module) │ Micropub, IndieAuth, │ -│ │ Webmention validation │ -└────────────────────────────────────────────────┘ -``` - -**Lessons from indieweb2-bastion**: -- Use provenance-style tracking for Webmention verification chains -- Apply bastion patterns for rate limiting endpoints -- Consider audit logging as a first-class feature - -### 5.1 Micropub Content Sanitizer -```php -Micropub::sanitizeContent(string $html, array $allowedTags = []): string -Micropub::validateEntry(array $mf2): ValidationResult -``` - -### 5.2 IndieAuth Helpers -```php -IndieAuth::verifyToken(string $token, string $endpoint): TokenResult -IndieAuth::validateMe(string $url): bool // Valid "me" URL -IndieAuth::validateRedirectUri(string $uri, string $clientId): bool -``` - -### 5.3 Webmention Validators -```php -Webmention::validateSource(string $url): bool // Not internal IP -Webmention::validateTarget(string $url, string $domain): bool -``` - -### 5.4 SSRF Prevention -```php -// Prevent Webmention SSRF attacks -Webmention::isInternalIp(string $ip): bool -Webmention::resolveAndValidate(string $url): ValidationResult -``` - ---- - -## Phase 6: Rate Limiting (v0.6.0) - -**Goal**: Protect against abuse without external dependencies. - -### 6.1 Token Bucket Implementation -```php -interface RateLimitStore { - public function get(string $key): ?TokenBucket; - public function set(string $key, TokenBucket $bucket, int $ttl): void; -} - -class MemoryStore implements RateLimitStore { ... } -class FileStore implements RateLimitStore { ... } -class RedisStore implements RateLimitStore { ... } // Optional -class ApcuStore implements RateLimitStore { ... } // Optional -``` - -### 6.2 Rate Limiter -```php -$limiter = new RateLimiter( - store: new FileStore('/tmp/ratelimit'), - capacity: 100, // requests - refillRate: 10, // per second -); - -if (!$limiter->attempt($clientIp)) { - http_response_code(429); - exit; -} -``` - ---- - -## Phase 7: Ecosystem Expansion (v0.7.0) - -**Goal**: Maximize adoption across PHP ecosystem. - -### 7.1 Compatibility Package - -Create `hyperpolymath/php-aegis-compat` for PHP 7.4+ environments. - -See [COMPATIBILITY.md](COMPATIBILITY.md) for full strategy. - -```bash -# PHP 7.4+ (legacy WordPress hosts) -composer require hyperpolymath/php-aegis-compat - -# PHP 8.1+ (recommended) -composer require hyperpolymath/php-aegis -``` - -### 7.2 WordPress Adapter - -WordPress-style function wrappers: -```php -aegis_html($input) // Maps to Sanitizer::html() -aegis_attr($input) // Maps to Sanitizer::attr() -aegis_js($input) // Maps to Sanitizer::js() -aegis_url($input) // Maps to Sanitizer::url() -aegis_send_security_headers() // Maps to Headers::secure() -``` - -### 7.3 Laravel Service Provider - -```php -// Auto-registered via package discovery -PhpAegis\Laravel\AegisServiceProvider::class - -// Blade directive -@aegis($userContent) - -// DI in controllers -public function store(Sanitizer $sanitizer) { ... } -``` - -### 7.4 Symfony Bundle - -```php -// config/bundles.php -PhpAegis\Symfony\AegisBundle::class => ['all' => true] - -// Twig filter -{{ user_content|aegis_html }} -``` - ---- - -## Differentiation Strategy - -### What WordPress Has (don't duplicate) -- `esc_html()`, `esc_attr()`, `esc_url()`, `esc_js()` -- `wp_kses()`, `wp_kses_post()` -- `sanitize_*()` functions -- Nonce verification - -### What php-aegis Provides (unique value) -| Feature | WordPress | Laravel | Symfony | php-aegis | -|---------|-----------|---------|---------|-----------| -| RDF/Turtle escaping | ❌ | ❌ | ❌ | ✅ | -| Security headers helper | ❌ | Partial | Partial | ✅ | -| IndieWeb validation | ❌ | ❌ | ❌ | ✅ | -| Zero dependencies | N/A | ❌ | ❌ | ✅ | -| PHP 8.1+ strict types | ❌ | ❌ | ❌ | ✅ | -| Rate limiting (no Redis) | ❌ | ❌ | ❌ | ✅ | - ---- - -## Success Metrics - -1. **Adoption**: Downloads on Packagist -2. **Integration**: Used in WordPress themes, Laravel packages -3. **Coverage**: CVE fixes attributable to php-aegis usage -4. **Community**: GitHub stars, issues, PRs - ---- - -## Timeline Philosophy - -Per project guidelines, no time estimates are provided. Work proceeds based on: -1. User demand (GitHub issues) -2. Security criticality -3. Contributor availability - -Phases can be reordered based on community feedback. - ---- - -*This roadmap reflects lessons learned from real WordPress integration.* diff --git a/SECURE_DEFAULTS.adoc b/SECURE_DEFAULTS.adoc new file mode 100644 index 0000000..cfc1e9b --- /dev/null +++ b/SECURE_DEFAULTS.adoc @@ -0,0 +1,927 @@ +== Secure Defaults Checklist + +This document provides a comprehensive checklist for secure PHP +development using php-aegis. Follow these guidelines to ensure your +application follows security best practices. + +=== Table of Contents + +* link:#owasp-top-10-mapping[OWASP Top 10 Mapping] +* link:#php-configuration[PHP Configuration] +* link:#input-validation[Input Validation] +* link:#output-sanitization[Output Sanitization] +* link:#http-security-headers[HTTP Security Headers] +* link:++#authentication--sessions++[Authentication & Sessions] +* link:#database-security[Database Security] +* link:#file-operations[File Operations] +* link:#cryptography[Cryptography] +* link:#error-handling[Error Handling] +* link:#cicd-security[CI/CD Security] +* link:#dependency-management[Dependency Management] + +''''' + +=== OWASP Top 10 Mapping + +This section maps php-aegis features and checklist items to the +https://owasp.org/Top10/[OWASP Top 10 2021] vulnerabilities. + +==== Summary Matrix + +[width="100%",cols="21%,26%,36%,17%",options="header",] +|=== +|OWASP ID |Vulnerability |php-aegis Coverage |Section +|A01:2021 |Broken Access Control |Partial (Headers) +|link:#http-security-headers[HTTP Headers] + +|A02:2021 |Cryptographic Failures |Guidelines +|link:#cryptography[Cryptography] + +|A03:2021 |Injection |*Full* (Validator, Sanitizer, TurtleEscaper) +|link:#input-validation[Input], link:#output-sanitization[Output] + +|A04:2021 |Insecure Design |Guidelines +|link:#secure-defaults-checklist[All Sections] + +|A05:2021 |Security Misconfiguration |*Full* (Headers) +|link:#http-security-headers[HTTP Headers], link:#php-configuration[PHP +Config] + +|A06:2021 |Vulnerable Components |Guidelines +|link:#dependency-management[Dependencies] + +|A07:2021 |Auth Failures |Guidelines +|link:++#authentication--sessions++[Authentication] + +|A08:2021 |Data Integrity Failures |Partial (CSP) +|link:#http-security-headers[HTTP Headers] + +|A09:2021 |Logging Failures |Guidelines |link:#error-handling[Error +Handling] + +|A10:2021 |SSRF |Partial (Validator) |link:#input-validation[Input +Validation] +|=== + +''''' + +==== A01:2021 - Broken Access Control + +*Risk:* Attackers access unauthorized resources or perform actions +outside their permissions. + +*php-aegis Mitigations:* + +[width="100%",cols="23%,43%,34%",options="header",] +|=== +|Control |php-aegis Feature |Code Example +|CSRF Prevention |`+Headers::secure()+` sets SameSite cookies +|`+Headers::secure()+` + +|Clickjacking |`+Headers::frameOptions('DENY')+` +|`+Headers::frameOptions()+` + +|CORS Policies |`+Headers::crossOrigin*Policy()+` +|`+Headers::crossOriginResourcePolicy()+` +|=== + +*Checklist:* - [ ] Use `+Headers::frameOptions('DENY')+` to prevent +clickjacking - [ ] Implement proper session management (see +link:++#authentication--sessions++[Authentication]) - [ ] Validate user +permissions on every request - [ ] Use CSRF tokens for state-changing +operations - [ ] Apply principle of least privilege + +''''' + +==== A02:2021 - Cryptographic Failures + +*Risk:* Sensitive data exposed due to weak/missing encryption. + +*php-aegis Mitigations:* + +[width="100%",cols="23%,43%,34%",options="header",] +|=== +|Control |php-aegis Feature |Code Example +|HTTPS Enforcement |`+Validator::httpsUrl()+` +|`+Validator::httpsUrl($url)+` + +|HSTS |`+Headers::strictTransportSecurity()+` +|`+Headers::strictTransportSecurity(31536000, true, true)+` +|=== + +*Checklist:* - [ ] Use `+Validator::httpsUrl()+` to reject non-HTTPS +URLs - [ ] Enable HSTS with `+Headers::strictTransportSecurity()+` - [ ] +Never use MD5/SHA1 for security (see link:#cryptography[Cryptography]) - +[ ] Use `+random_bytes()+` for secure random data - [ ] Use Argon2id for +password hashing + +*CI Enforcement:* + +[source,yaml] +---- +# In php-lint.yml - checks for weak cryptography +- name: Check weak cryptography + run: grep -rEn 'md5\s*\(|sha1\s*\(' --include="*.php" src/ +---- + +''''' + +==== A03:2021 - Injection + +*Risk:* Untrusted data interpreted as commands (SQL, XSS, OS, LDAP, +Turtle). + +*php-aegis Mitigations:* + +[width="100%",cols="29%,40%,31%",options="header",] +|=== +|Attack Type |php-aegis Feature |Code Example +|XSS (HTML) |`+Sanitizer::html()+` |`+echo Sanitizer::html($input)+` + +|XSS (Attr) |`+Sanitizer::attr()+` +|`+value=""+` + +|XSS (JS) |`+Sanitizer::js()+` |`+var x = +` + +|Path Traversal |`+Validator::safeFilename()+` +|`+Validator::safeFilename($name)+` + +|Null Byte |`+Validator::noNullBytes()+` +|`+Validator::noNullBytes($path)+` + +|RDF/SPARQL |`+TurtleEscaper::string()+` |`+TurtleEscaper::literal($v)+` + +|URL Injection |`+Sanitizer::url()+` +|`+href=""+` + +|JSON Injection |`+Sanitizer::json()+` |`+Sanitizer::json($data)+` +|=== + +*Checklist:* - [ ] Use `+Sanitizer::html()+` for all HTML output - [ ] +Use `+Sanitizer::attr()+` for HTML attributes - [ ] Use +`+Sanitizer::js()+` for inline JavaScript - [ ] Use +`+Sanitizer::json()+` for JSON responses - [ ] Use +`+TurtleEscaper::literal()+` for RDF/Turtle data - [ ] Use +`+Validator::safeFilename()+` for file operations - [ ] Use prepared +statements for ALL database queries + +*CI Enforcement:* + +[source,yaml] +---- +# In php-lint.yml - checks for injection patterns +- name: Check dangerous functions + run: | + grep -rEn 'eval\s*\(|exec\s*\(' --include="*.php" src/ + grep -rEn 'echo\s+\$_(GET|POST)' --include="*.php" src/ +---- + +''''' + +==== A04:2021 - Insecure Design + +*Risk:* Missing or ineffective security controls in application design. + +*php-aegis Mitigations:* + +[width="100%",cols="25%,50%,25%",options="header",] +|=== +|Control |php-aegis Feature |Purpose +|Secure Defaults |`+Headers::secure()+` |One-call security setup + +|Type Safety |All methods require `+string+` types |Prevents type +confusion + +|Fail Secure |Validators return `+false+` on invalid input |Reject by +default +|=== + +*Checklist:* - [ ] Call `+Headers::secure()+` early in every request - [ +] Use `+declare(strict_types=1)+` in all PHP files - [ ] Validate before +processing, sanitize before output - [ ] Reject invalid input (don’t try +to "`fix`" it) - [ ] Design with defense in depth + +''''' + +==== A05:2021 - Security Misconfiguration + +*Risk:* Missing security hardening, default credentials, verbose errors. + +*php-aegis Mitigations:* + +[width="100%",cols="36%,36%,28%",options="header",] +|=== +|Misconfiguration |php-aegis Feature |Code Example +|Missing CSP |`+Headers::contentSecurityPolicy()+` +|`+Headers::secure()+` + +|Missing HSTS |`+Headers::strictTransportSecurity()+` +|`+Headers::secure()+` + +|Server Leakage |`+Headers::removeInsecureHeaders()+` +|`+Headers::secure()+` + +|MIME Sniffing |`+Headers::contentTypeOptions()+` |`+Headers::secure()+` + +|Missing Permissions-Policy |`+Headers::permissionsPolicy()+` +|`+Headers::secure()+` +|=== + +*Headers set by `+Headers::secure()+`:* + +.... +Content-Security-Policy: default-src 'self' +Strict-Transport-Security: max-age=31536000; includeSubDomains +X-Frame-Options: DENY +X-Content-Type-Options: nosniff +X-XSS-Protection: 1; mode=block +Referrer-Policy: strict-origin-when-cross-origin +Permissions-Policy: geolocation=(), camera=(), microphone=(), payment=() +.... + +*Checklist:* - [ ] Call `+Headers::secure()+` on every response - [ ] +Configure PHP securely (see link:#php-configuration[PHP Configuration]) +- [ ] Disable `+display_errors+` in production - [ ] Remove default +credentials and accounts - [ ] Review all security headers with +https://securityheaders.com[securityheaders.com] + +''''' + +==== A06:2021 - Vulnerable and Outdated Components + +*Risk:* Using libraries with known vulnerabilities. + +*php-aegis Design:* - *Zero runtime dependencies* - Only PHP 8.1+ +built-ins - No vulnerable dependencies to track in production + +*Checklist:* - [ ] Run `+composer audit+` on every CI build - [ ] Keep +PHP version updated (8.1+ required) - [ ] Review dev dependencies before +adding - [ ] Enable Dependabot/Renovate for automatic updates + +*CI Enforcement:* + +[source,yaml] +---- +# In php-lint.yml +- name: Run Composer audit + run: composer audit --format=plain +---- + +''''' + +==== A07:2021 - Identification and Authentication Failures + +*Risk:* Weak passwords, session hijacking, credential stuffing. + +*php-aegis Mitigations:* + +[width="100%",cols="25%,50%,25%",options="header",] +|=== +|Control |php-aegis Feature |Purpose +|Session Security |`+Headers::secure()+` sets cookie flags |SameSite, +Secure +|=== + +*Checklist:* - [ ] Use `+password_hash()+` with `+PASSWORD_ARGON2ID+` - +[ ] Use `+password_verify()+` for constant-time comparison - [ ] +Regenerate session ID on login (`+session_regenerate_id(true)+`) - [ ] +Set session cookie flags: HttpOnly, Secure, SameSite=Strict - [ ] +Implement rate limiting for authentication - [ ] Use MFA for sensitive +operations + +''''' + +==== A08:2021 - Software and Data Integrity Failures + +*Risk:* Untrusted code execution, insecure CI/CD, missing integrity +checks. + +*php-aegis Mitigations:* + +[width="100%",cols="25%,50%,25%",options="header",] +|=== +|Control |php-aegis Feature |Purpose +|CSP |`+Headers::contentSecurityPolicy()+` |Prevents inline script +injection + +|SRI Support |Design for external script verification |Subresource +Integrity +|=== + +*Checklist:* - [ ] Use Content-Security-Policy to block inline scripts - +[ ] Pin GitHub Actions to commit SHAs (not tags) - [ ] Verify +`+composer.lock+` in CI builds - [ ] Sign commits with GPG - [ ] Use +Subresource Integrity for CDN resources + +*CI Enforcement:* + +[source,yaml] +---- +# Pin actions to SHA for integrity +- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 +---- + +''''' + +==== A09:2021 - Security Logging and Monitoring Failures + +*Risk:* Insufficient logging, missing alerting, undetected breaches. + +*Checklist:* - [ ] Log authentication attempts (success and failure) - [ +] Log access control failures - [ ] Log input validation failures +(potential attacks) - [ ] Don’t log sensitive data (passwords, tokens, +PII) - [ ] Set up alerting for anomalous patterns - [ ] Monitor error +logs for security issues + +*Error Handler Pattern:* + +[source,php] +---- +set_exception_handler(function (Throwable $e): void { + // Log for operators + error_log(sprintf('[%s] %s', get_class($e), $e->getMessage())); + + // Generic response to users + http_response_code(500); + echo json_encode(['error' => 'An unexpected error occurred']); + exit(1); +}); +---- + +''''' + +==== A10:2021 - Server-Side Request Forgery (SSRF) + +*Risk:* Attacker forces server to make requests to unintended +destinations. + +*php-aegis Mitigations:* + +[width="100%",cols="23%,43%,34%",options="header",] +|=== +|Control |php-aegis Feature |Code Example +|URL Validation |`+Validator::url()+` |`+Validator::url($url)+` + +|HTTPS Enforcement |`+Validator::httpsUrl()+` +|`+Validator::httpsUrl($url)+` + +|Hostname Validation |`+Validator::hostname()+` +|`+Validator::hostname($host)+` + +|IP Validation |`+Validator::ip()+`, `+ipv4()+`, `+ipv6()+` +|`+Validator::ip($ip)+` +|=== + +*Checklist:* - [ ] Validate all user-supplied URLs with +`+Validator::url()+` - [ ] Prefer `+Validator::httpsUrl()+` to enforce +HTTPS - [ ] Maintain allowlist of permitted domains/IPs - [ ] Block +requests to internal/private IP ranges - [ ] Don’t follow redirects +blindly + +*Safe URL Fetching:* + +[source,php] +---- +use PhpAegis\Validator; + +function safeFetch(string $url): string { + // Validate URL format + if (!Validator::httpsUrl($url)) { + throw new InvalidArgumentException('Invalid or non-HTTPS URL'); + } + + // Parse and validate hostname + $host = parse_url($url, PHP_URL_HOST); + if (!$host || !Validator::domain($host)) { + throw new InvalidArgumentException('Invalid hostname'); + } + + // Block internal/private IPs (allowlist approach is better) + $ip = gethostbyname($host); + if (filter_var($ip, FILTER_VALIDATE_IP, + FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { + throw new InvalidArgumentException('Private/reserved IP not allowed'); + } + + // Now safe to fetch + return file_get_contents($url); +} +---- + +''''' + +==== OWASP Coverage Summary + +[cols=",",options="header",] +|=== +|php-aegis Class |OWASP Categories Addressed +|`+Validator+` |A03, A10 +|`+Sanitizer+` |A03 +|`+Headers+` |A01, A02, A04, A05, A08 +|`+TurtleEscaper+` |A03 +|=== + +*Legend:* - *Full Coverage*: php-aegis provides direct protection - +*Partial Coverage*: php-aegis helps but additional measures needed - +*Guidelines*: Documentation and checklists provided + +''''' + +=== PHP Configuration + +==== Required Settings + +[source,ini] +---- +; Strict error reporting (development) +error_reporting = E_ALL +display_errors = Off +log_errors = On + +; Session security +session.cookie_httponly = 1 +session.cookie_secure = 1 +session.cookie_samesite = Strict +session.use_strict_mode = 1 +session.use_only_cookies = 1 + +; Disable dangerous functions +disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec,parse_ini_file,show_source,eval + +; File upload limits +upload_max_filesize = 10M +max_file_uploads = 5 + +; Exposure reduction +expose_php = Off +---- + +==== Checklist + +* [ ] `+declare(strict_types=1)+` at top of every PHP file +* [ ] Error display disabled in production (`+display_errors = Off+`) +* [ ] Error logging enabled (`+log_errors = On+`) +* [ ] Dangerous functions disabled where not needed +* [ ] PHP version exposure disabled (`+expose_php = Off+`) +* [ ] Session cookies are HttpOnly and Secure +* [ ] Appropriate memory and execution limits set + +''''' + +=== Input Validation + +==== Using php-aegis Validator + +[source,php] +---- +use PhpAegis\Validator; + +// Always validate before use +$email = Validator::email($_POST['email'] ?? '') ? $_POST['email'] : null; +$url = Validator::httpsUrl($_POST['website'] ?? '') ? $_POST['website'] : null; +$id = Validator::uuid($_GET['id'] ?? '') ? $_GET['id'] : null; +---- + +==== Checklist + +* [ ] *Never trust user input* - validate ALL external data +* [ ] Use `+Validator::email()+` for email addresses +* [ ] Use `+Validator::httpsUrl()+` for URLs (enforce HTTPS) +* [ ] Use `+Validator::uuid()+` for identifiers +* [ ] Use `+Validator::int()+` with min/max bounds for integers +* [ ] Use `+Validator::noNullBytes()+` to prevent null byte injection +* [ ] Use `+Validator::safeFilename()+` for user-provided filenames +* [ ] Use `+Validator::printable()+` for text that should have no +control chars +* [ ] Reject invalid input rather than attempting to "`fix`" it +* [ ] Validate data types, lengths, formats, and ranges +* [ ] Use allowlists over denylists where possible + +==== Validation Priority + +[cols=",,",options="header",] +|=== +|Input Source |Risk Level |Required Validation +|`+$_GET+` |High |Always validate +|`+$_POST+` |High |Always validate +|`+$_FILES+` |Critical |Validate + scan +|`+$_COOKIE+` |High |Always validate +|`+$_SERVER+` |Medium |Validate if user-influenced +|Database |Medium |Validate on retrieval +|APIs |Medium |Validate responses +|=== + +''''' + +=== Output Sanitization + +==== Using php-aegis Sanitizer + +[source,php] +---- +use PhpAegis\Sanitizer; + +// HTML context +echo Sanitizer::html($userInput); + +// HTML attribute context +echo ''; + +// JavaScript context +echo ''; + +// URL context +echo 'Link'; + +// CSS context (limited support - prefer external stylesheets) +echo '
'; +---- + +==== Checklist + +* [ ] *Context-aware escaping* - use the right method for each context +* [ ] Use `+Sanitizer::html()+` for HTML body content +* [ ] Use `+Sanitizer::attr()+` for HTML attributes +* [ ] Use `+Sanitizer::js()+` for inline JavaScript +* [ ] Use `+Sanitizer::url()+` for URL components +* [ ] Use `+Sanitizer::json()+` for JSON output +* [ ] Use `+Sanitizer::filename()+` before file operations +* [ ] Never use `+htmlspecialchars()+` alone - it’s not context-aware +* [ ] Never output user data in `+'; - -// URL context -echo 'Link'; - -// CSS context (limited support - prefer external stylesheets) -echo '
'; -``` - -### Checklist - -- [ ] **Context-aware escaping** - use the right method for each context -- [ ] Use `Sanitizer::html()` for HTML body content -- [ ] Use `Sanitizer::attr()` for HTML attributes -- [ ] Use `Sanitizer::js()` for inline JavaScript -- [ ] Use `Sanitizer::url()` for URL components -- [ ] Use `Sanitizer::json()` for JSON output -- [ ] Use `Sanitizer::filename()` before file operations -- [ ] Never use `htmlspecialchars()` alone - it's not context-aware -- [ ] Never output user data in `+` |Complete removal or +HTML encoding + +|*Event Handlers* |`++` |Attribute +stripping + +|*JavaScript URLs* |`++` |URL +validation and rejection + +|*SVG Attacks* |`++` |SVG sanitization or +removal + +|*Data URIs* |`++` |Data URI blocking + +|*Object/Embed* |`++` |Tag +removal + +|*Iframe Injection* |`+