From 39f7e2221694c9dc945cfadf4201dea1a6a1bb96 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 24 Aug 2026 08:42:26 +0100 Subject: [PATCH] refactor: migrate repository documentation from Markdown to AsciiDoc --- .meta/REQUIRED-FILES.adoc | 58 ++ .meta/REQUIRED-FILES.md | 53 -- ARCHITECTURE.adoc | 48 ++ ARCHITECTURE.md | 47 -- CHANGELOG.adoc | 73 +++ CHANGELOG.md | 70 --- CODE_OF_CONDUCT.adoc | 24 + CODE_OF_CONDUCT.md | 27 - COMPREHENSIVE-ROADMAP.adoc | 373 +++++++++++++ COMPREHENSIVE-ROADMAP.md | 390 -------------- CONTRIBUTING.adoc | 109 ++++ CONTRIBUTING.md | 116 ---- GOVERNANCE.adoc | 60 +++ GOVERNANCE.md | 60 --- PROGRESS-SUMMARY.adoc | 292 ++++++++++ PROGRESS-SUMMARY.md | 276 ---------- PROOF-NEEDS.adoc | 63 +++ PROOF-NEEDS.md | 49 -- SECURITY.md => SECURITY.adoc | 24 +- TEST-NEEDS.adoc | 121 +++++ TEST-NEEDS.md | 83 --- TOPOLOGY.md => TOPOLOGY.adoc | 39 +- docs/IMPLEMENTATION-TRACKER.adoc | 240 +++++++++ docs/IMPLEMENTATION-TRACKER.md | 201 ------- ...ORATION.md => INDIEWEB-COLLABORATION.adoc} | 200 ++++--- docs/INTEGRATION-SUMMARY.adoc | 275 ++++++++++ docs/INTEGRATION-SUMMARY.md | 217 -------- ...IS-HANDOVER.md => PHP-AEGIS-HANDOVER.adoc} | 458 +++++++++------- docs/{ROADMAP.md => ROADMAP.adoc} | 401 ++++++++------ docs/{STANDALONE.md => STANDALONE.adoc} | 310 ++++++----- docs/TARGET-AUDIENCE.adoc | 256 +++++++++ docs/TARGET-AUDIENCE.md | 231 -------- docs/UPSTREAM-ISSUES.adoc | 338 ++++++++++++ docs/UPSTREAM-ISSUES.md | 334 ------------ 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 - test-plugins/TEST-REPORT.adoc | 500 ++++++++++++++++++ test-plugins/TEST-REPORT.md | 424 --------------- test/README.adoc | 120 +++++ test/README.md | 106 ---- 44 files changed, 3867 insertions(+), 3397 deletions(-) create mode 100644 .meta/REQUIRED-FILES.adoc delete mode 100644 .meta/REQUIRED-FILES.md 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 COMPREHENSIVE-ROADMAP.adoc delete mode 100644 COMPREHENSIVE-ROADMAP.md create mode 100644 CONTRIBUTING.adoc delete mode 100644 CONTRIBUTING.md create mode 100644 GOVERNANCE.adoc delete mode 100644 GOVERNANCE.md create mode 100644 PROGRESS-SUMMARY.adoc delete mode 100644 PROGRESS-SUMMARY.md create mode 100644 PROOF-NEEDS.adoc delete mode 100644 PROOF-NEEDS.md rename SECURITY.md => SECURITY.adoc (52%) create mode 100644 TEST-NEEDS.adoc delete mode 100644 TEST-NEEDS.md rename TOPOLOGY.md => TOPOLOGY.adoc (89%) create mode 100644 docs/IMPLEMENTATION-TRACKER.adoc delete mode 100644 docs/IMPLEMENTATION-TRACKER.md rename docs/{INDIEWEB-COLLABORATION.md => INDIEWEB-COLLABORATION.adoc} (81%) create mode 100644 docs/INTEGRATION-SUMMARY.adoc delete mode 100644 docs/INTEGRATION-SUMMARY.md rename docs/{PHP-AEGIS-HANDOVER.md => PHP-AEGIS-HANDOVER.adoc} (60%) rename docs/{ROADMAP.md => ROADMAP.adoc} (73%) rename docs/{STANDALONE.md => STANDALONE.adoc} (54%) create mode 100644 docs/TARGET-AUDIENCE.adoc delete mode 100644 docs/TARGET-AUDIENCE.md create mode 100644 docs/UPSTREAM-ISSUES.adoc delete mode 100644 docs/UPSTREAM-ISSUES.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 test-plugins/TEST-REPORT.adoc delete mode 100644 test-plugins/TEST-REPORT.md create mode 100644 test/README.adoc delete mode 100644 test/README.md diff --git a/.meta/REQUIRED-FILES.adoc b/.meta/REQUIRED-FILES.adoc new file mode 100644 index 0000000..3a85933 --- /dev/null +++ b/.meta/REQUIRED-FILES.adoc @@ -0,0 +1,58 @@ +== Required Repository Files + +The following files *MUST* be present and kept up-to-date in every +repository: + +=== Mandatory Dotfiles + +[cols=",",options="header",] +|=== +|File |Purpose +|`+.gitignore+` |Exclude build artifacts, secrets, and temp files +|`+.gitattributes+` |Enforce LF line endings and diff settings +|`+.editorconfig+` |Consistent editor settings across IDEs +|`+.tool-versions+` |asdf version pinning for reproducible builds +|=== + +=== Mandatory SCM Files + +[cols=",",options="header",] +|=== +|File |Purpose +|`+META.scm+` |Architecture decisions, development practices +|`+STATE.scm+` |Project state, phase, milestones +|`+ECOSYSTEM.scm+` |Ecosystem positioning, related projects +|`+PLAYBOOK.scm+` |Executable plans, procedures +|`+AGENTIC.scm+` |AI agent operational gating +|`+NEUROSYM.scm+` |Symbolic semantics, proof obligations +|=== + +=== Build System + +[cols=",",options="header",] +|=== +|File |Purpose +|`+justfile+` |Task runner (replaces Makefile) +|`+Mustfile+` |Deployment state contract +|=== + +*IMPORTANT*: Makefiles are FORBIDDEN. Use `+just+` for all tasks. + +=== Validation + +These files are checked by: - CI workflow validation - Pre-commit hooks +(when configured) - Repository standardization scripts + +=== Updates + +When updating these files: 1. Use templates from `+rsr-template-repo+` +as reference 2. Ensure SPDX license header is present 3. Test changes +locally before pushing 4. Keep language-specific sections relevant to +the repo + +=== See Also + +* https://github.com/hyperpolymath/rhodium-standard-repositories[RSR +(Rhodium Standard Repositories)] +* https://github.com/hyperpolymath/mustfile[Mustfile Specification] +* https://github.com/hyperpolymath/meta-scm[SCM Format Family] diff --git a/.meta/REQUIRED-FILES.md b/.meta/REQUIRED-FILES.md deleted file mode 100644 index b06e206..0000000 --- a/.meta/REQUIRED-FILES.md +++ /dev/null @@ -1,53 +0,0 @@ -# Required Repository Files - -The following files **MUST** be present and kept up-to-date in every repository: - -## Mandatory Dotfiles - -| File | Purpose | -|------|---------| -| `.gitignore` | Exclude build artifacts, secrets, and temp files | -| `.gitattributes` | Enforce LF line endings and diff settings | -| `.editorconfig` | Consistent editor settings across IDEs | -| `.tool-versions` | asdf version pinning for reproducible builds | - -## Mandatory SCM Files - -| File | Purpose | -|------|---------| -| `META.scm` | Architecture decisions, development practices | -| `STATE.scm` | Project state, phase, milestones | -| `ECOSYSTEM.scm` | Ecosystem positioning, related projects | -| `PLAYBOOK.scm` | Executable plans, procedures | -| `AGENTIC.scm` | AI agent operational gating | -| `NEUROSYM.scm` | Symbolic semantics, proof obligations | - -## Build System - -| File | Purpose | -|------|---------| -| `justfile` | Task runner (replaces Makefile) | -| `Mustfile` | Deployment state contract | - -**IMPORTANT**: Makefiles are FORBIDDEN. Use `just` for all tasks. - -## Validation - -These files are checked by: -- CI workflow validation -- Pre-commit hooks (when configured) -- Repository standardization scripts - -## Updates - -When updating these files: -1. Use templates from `rsr-template-repo` as reference -2. Ensure SPDX license header is present -3. Test changes locally before pushing -4. Keep language-specific sections relevant to the repo - -## See Also - -- [RSR (Rhodium Standard Repositories)](https://github.com/hyperpolymath/rhodium-standard-repositories) -- [Mustfile Specification](https://github.com/hyperpolymath/mustfile) -- [SCM Format Family](https://github.com/hyperpolymath/meta-scm) 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..8396d6c --- /dev/null +++ b/CHANGELOG.adoc @@ -0,0 +1,73 @@ +== Changelog + +All notable changes to `+sanctify-php+` 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 stapeln.toml container definition +* feat: deploy UX Manifesto infrastructure +* feat: add CLADE.a2ml — clade taxonomy declaration +* feat(ci): enable Hypatia scanning +* feat: implement security analysis stubs with post-quantum crypto +detection + +==== Fixed + +* fix(ci): bump a2ml/k9-validate-action pins to canonical (#29) +* fix(ci): sync hypatia-scan.yml to canonical (#28) +* fix(ci): build Hypatia escript from repo root (estate dogfood drift) +* fix(ci): repair YAML block-scalar in workflow-linter Check Permissions +step (#26) +* fix: remove tracked build artifacts, update gitignore +* fix(scorecard): enforce granular permissions and add fuzzing +placeholder +* fix(ci): Resolve workflow-linter self-matching and metadata issues +* fix: correct email jonathan.jewell → j.d.a.jewell +* fix: global AGPL-3.0-or-later → PMPL-1.0-or-later replacement +* fix(license): SPDX AGPL-3.0 → PMPL-1.0-or-later in dotfiles + +==== 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 CONTRIBUTING.md +* docs: add checkpoint files for state tracking +* docs: update license from AGPL to PMPL + +==== CI + +* ci: redistribute concurrency-cancel guard to read-only check workflows +(#31) +* ci: bump actions/upload-artifact SHA to current v4 (#25) +* ci: SHA-pin hyperpolymath validate-actions in dogfood-gate +* ci: restore Dependabot security path + wire auto-merge +* ci: deploy dogfood-gate, add Groove manifest and 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 160c4d5..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,70 +0,0 @@ - - -# Changelog - -All notable changes to `sanctify-php` 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 stapeln.toml container definition -- feat: deploy UX Manifesto infrastructure -- feat: add CLADE.a2ml — clade taxonomy declaration -- feat(ci): enable Hypatia scanning -- feat: implement security analysis stubs with post-quantum crypto detection - -### Fixed - -- fix(ci): bump a2ml/k9-validate-action pins to canonical (#29) -- fix(ci): sync hypatia-scan.yml to canonical (#28) -- fix(ci): build Hypatia escript from repo root (estate dogfood drift) -- fix(ci): repair YAML block-scalar in workflow-linter Check Permissions step (#26) -- fix: remove tracked build artifacts, update gitignore -- fix(scorecard): enforce granular permissions and add fuzzing placeholder -- fix(ci): Resolve workflow-linter self-matching and metadata issues -- fix: correct email jonathan.jewell → j.d.a.jewell -- fix: global AGPL-3.0-or-later → PMPL-1.0-or-later replacement -- fix(license): SPDX AGPL-3.0 → PMPL-1.0-or-later in dotfiles - -### 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 CONTRIBUTING.md -- docs: add checkpoint files for state tracking -- docs: update license from AGPL to PMPL - -### CI - -- ci: redistribute concurrency-cancel guard to read-only check workflows (#31) -- ci: bump actions/upload-artifact SHA to current v4 (#25) -- ci: SHA-pin hyperpolymath validate-actions in dogfood-gate -- ci: restore Dependabot security path + wire auto-merge -- ci: deploy dogfood-gate, add Groove manifest and 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..bd2a83c --- /dev/null +++ b/CODE_OF_CONDUCT.adoc @@ -0,0 +1,24 @@ +== Contributor Covenant Code of Conduct + +=== Our Pledge + +We pledge to make participation a harassment-free experience for +everyone. + +=== Our Standards + +*Positive behavior:* * Using welcoming language * Being respectful of +differing viewpoints * Accepting constructive criticism * Focusing on +what is best for the community + +*Unacceptable behavior:* * Harassment, trolling, or personal attacks * +Publishing private information without permission + +=== Enforcement + +Report issues to the maintainers. All complaints will be reviewed. + +=== Attribution + +Adapted from https://www.contributor-covenant.org/[Contributor Covenant] +v2.1. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index caeda1c..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,27 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We pledge to make participation a harassment-free experience for everyone. - -## Our Standards - -**Positive behavior:** -* Using welcoming language -* Being respectful of differing viewpoints -* Accepting constructive criticism -* Focusing on what is best for the community - -**Unacceptable behavior:** -* Harassment, trolling, or personal attacks -* Publishing private information without permission - -## Enforcement - -Report issues to the maintainers. All complaints will be reviewed. - -## Attribution - -Adapted from [Contributor Covenant](https://www.contributor-covenant.org/) v2.1. - diff --git a/COMPREHENSIVE-ROADMAP.adoc b/COMPREHENSIVE-ROADMAP.adoc new file mode 100644 index 0000000..e55354e --- /dev/null +++ b/COMPREHENSIVE-ROADMAP.adoc @@ -0,0 +1,373 @@ +== Sanctify-PHP Comprehensive Implementation Roadmap + +*Target: 40% → 100% Completion* *Vision: Production-Ready PHP Security +Analysis & Hardening Tool* + +=== Current Status Assessment (40%) + +==== ✅ Implemented (Strong Foundation) + +* *AST*: Comprehensive PHP 8.x AST with modern features (attributes, +enums, match, etc.) +* *Parser*: Megaparsec-based PHP parser (basic structures working) +* *Security Analysis*: Extensive vulnerability detection +** SQL injection, XSS, CSRF, command injection +** Path traversal, unsafe deserialization +** Weak crypto (with modern recommendations: SHAKE3-256/BLAKE3) +** Hardcoded secrets detection +** Dangerous function flagging +* *Transform/Sanitize*: WordPress-specific security transformations +** Output escaping (esc_html, esc_attr, etc.) +** Input sanitization detection +** SQL preparation wrapping +** Superglobal sanitization +** Exit after redirect +* *WordPress*: WordPress-specific constraint checking +* *Core Modules*: Config, Report, Ruleset (exist but need verification) + +==== ⚠️ Needs Completion/Enhancement (60% Gap) + +[arabic] +. *Parser*: Needs full PHP 8.x expression/statement coverage +. *Emit*: PHP code generation from AST (critical for transformations) +. *Taint Analysis*: Data flow tracking needs completion +. *Type Inference*: PHP type system inference engine +. *Dead Code*: Unused code detection +. *CLI*: Production-ready command-line interface +. *Testing*: Comprehensive test suite +. *Documentation*: User guide, API docs, examples + +''''' + +=== Phase 1: Core Completion (8-12h) - CRITICAL + +==== 1.1 Complete Parser (3-4h) ✅ COMPLETE + +*Priority: CRITICAL* - Nothing works without a complete parser + +* [x] *Expression parsing completion* +** Match expressions (PHP 8.0) ✓ +** Null coalescing assignment (??=) ✓ +** Spread operator in arrays ✓ +** Arrow functions with attributes ✓ +** Ternary and elvis operators ✓ +** Method calls and property access (including nullsafe) ✓ +* [x] *Statement parsing completion* +** Try/catch with multiple exception types ✓ +** Switch/match comprehensive coverage ✓ +** Declare directives (ticks, encoding) ✓ +** Global, static, unset statements ✓ +* [x] *Modern PHP 8.x features* +** Readonly classes (PHP 8.2) ✓ +** DNF types (PHP 8.2) - `+(A&B)|(C&D)+` ✓ +** Constants in traits ✓ +** Attributes on all declarations ✓ +** Interface and enum parsing ✓ +** Constructor property promotion ✓ +* [ ] *Robustness* (deferred to Phase 5) +** Better error recovery (don’t fail on single parse error) +** Preserve whitespace/comments as metadata (for code generation) +** Line/column tracking for all nodes (partially done) + +==== 1.2 Complete Emit - Code Generation (3-4h) ✅ COMPLETE + +*Priority: CRITICAL* - Required for all transformations + +* [x] *Pretty printer from AST* +** Generate readable PHP code ✓ +** All statements (match, try/catch, declare, global, static, unset) ✓ +** All expressions (closures, arrow functions, yield, throw) ✓ +** All declarations (interface, trait, enum, functions, classes) ✓ +** Attributes on all declarations ✓ +** DNF types with proper parenthesization ✓ +** Constructor property promotion ✓ +* [ ] *Transformation output* (deferred to Phase 4) +** Apply transform passes to AST +** Emit modified code +** Diff generation (show what changed) +* [ ] *Code style enforcement* (deferred to Phase 4) +** PSR-12 compliance option +** WordPress coding standards option +** Configurable brace style, spacing + +==== 1.3 Type Inference Completion (2-3h) + +*Priority: HIGH* - Enables automatic type hint addition + +* [ ] *Basic type inference* +** Infer return types from function bodies +** Infer parameter types from usage +** Propagate types through assignments +* [ ] *WordPress type inference* +** Recognize WordPress function signatures +** Hook parameter type inference +** WP_Query, WP_Post type awareness +* [ ] *Generics awareness* +** array inference +** Collection type tracking + +''''' + +=== Phase 2: Advanced Analysis (8-10h) + +==== 2.1 Complete Taint Tracking (3-4h) + +*Priority: HIGH* - Critical for security analysis accuracy + +* [ ] *Data flow graph* +** Build control flow graph +** Track tainted data propagation +** Source → Sink analysis +* [ ] *Taint sources* +** Superglobals ($_GET, $_POST, $_COOKIE, etc.) +** Database query results (trust context) +** User input functions (file_get_contents, etc.) +* [ ] *Sanitizers recognition* +** WordPress sanitization functions +** PHP filter functions +** Custom sanitizer patterns +* [ ] *Sinks* +** SQL queries, shell commands +** File operations, eval +** Output (echo, print) + +==== 2.2 WordPress-Specific Deep Analysis (2-3h) + +*Priority: MEDIUM* - Differentiator for WP developers + +* [ ] *Hook analysis* +** Detect priority conflicts +** Find missing/misplaced hooks +** Identify wrong hook usage +* [ ] *Capability checking* +** Find missing current_user_can() checks +** Detect privilege escalation risks +** Admin vs frontend context +* [ ] *Nonce verification* +** Comprehensive CSRF detection +** Find form submissions without nonces +** AJAX handler nonce checking +* [ ] *Database query analysis* +** $wpdb->prepare() compliance +** Direct SQL detection +** Table prefix usage +* [ ] *Internationalization* +** Find untranslated strings +** Detect missing text domains +** Check escaping+translation combos + +==== 2.3 Advanced Security Checks (3-4h) + +*Priority: HIGH* - Beyond basic OWASP + +* [ ] *Time-of-check-time-of-use (TOCTOU)* +** File operation race conditions +** Permission check bypasses +* [ ] *Regular expression DoS (ReDoS)* +** Detect catastrophic backtracking patterns +** Flag unsafe regex in preg_* functions +* [ ] *Server-Side Request Forgery (SSRF)* +** wp_remote_get/post with user input +** file_get_contents with URLs +* [ ] *XML External Entity (XXE)* +** simplexml_load_* without disable_entity_loader +** DOMDocument loadXML safety +* [ ] *Insecure direct object references* +** Missing ownership checks on database queries +** User ID manipulation detection +* [ ] *Mass assignment vulnerabilities* +** Unvalidated array assignments to models + +''''' + +=== Phase 3: Production CLI & Tooling (6-8h) + +==== 3.1 Enhanced CLI (3-4h) ✅ COMPLETE + +*Priority: HIGH* - User-facing interface + +* [x] *Command improvements* +** `+sanctify analyze+` - full analysis with report ✓ +** `+sanctify fix --interactive+` - interactive fixing with previews ✓ +** `+sanctify fix --diff+` - show unified diff of changes ✓ +** `+sanctify --watch+` - watch mode for development ✓ +* [x] *Output formats* +** JSON (machine-readable) ✓ +** SARIF (GitHub/GitLab integration) ✓ +** HTML (rich visualization) ✓ +** Terminal (text output) ✓ +* [x] *Filtering & targeting* +** `+--severity=high,critical+` - filter by severity ✓ +** `+--type=sql,xss+` - filter by vulnerability type ✓ +** `+--in-place+` - apply fixes to files ✓ +** `+--verbose+` - detailed output ✓ +* [ ] *Performance* (deferred to Phase 6) +** Parallel file processing +** Incremental analysis (only changed files) +** Result caching +** `+.sanctifyignore+` support + +==== 3.2 Integration & Export (2-3h) + +*Priority: MEDIUM* - DevOps integration + +* [ ] *CI/CD integration* +** Exit codes for CI failure +** GitHub Actions integration +** GitLab CI templates +** Pre-commit hooks +* [ ] *IDE integration preparation* +** Language Server Protocol (LSP) foundations +** JSON-RPC interface +** Real-time analysis hooks +* [ ] *Configuration export* +** php.ini hardening recommendations +** nginx/Apache security headers +** Guix/Nix package definitions +** Docker security options + +==== 3.3 Reporting & Metrics (1-2h) + +*Priority: MEDIUM* - Visibility and tracking + +* [ ] *Comprehensive reports* +** Executive summary +** Trend analysis (compare with previous scans) +** Remediation guidance with code examples +** Risk scoring +* [ ] *Metrics & dashboards* +** Security score calculation +** Issue distribution (by type, severity, file) +** Fix effort estimation +** Progress tracking + +''''' + +=== Phase 4: Advanced Transformations (6-8h) + +==== 4.1 Automatic Fixes (4-5h) + +*Priority: HIGH* - Save developer time + +* [ ] *Safe auto-fixes* (zero-risk, always apply) +** Add `+declare(strict_types=1)+` +** Add ABSPATH check to WP files +** Convert `+rand()+` → `+random_int()+` +** Add `+exit+` after `+wp_redirect()+` +** Fix missing text domains in i18n functions +* [ ] *Semi-automatic fixes* (suggest with preview) +** Wrap superglobals with sanitizers +** Replace `+$wpdb->query()+` with `+$wpdb->prepare()+` +** Add nonce verification scaffolding +** Wrap `+echo+` with `+esc_html()+` +* [ ] *Type hint addition* +** Infer and add parameter types +** Infer and add return types +** Add property types +* [ ] *Modernization* +** Convert old array() → [] +** Convert isset() chains → null coalescing +** Convert create_function() → closures + +==== 4.2 Code Quality Transformations (2-3h) + +*Priority: MEDIUM* - Beyond security + +* [ ] *PSR compliance* +** Naming conventions +** File organization +** Docblock generation +* [ ] *WordPress standards* +** Yoda conditions +** Brace style +** Hook documentation + +''''' + +=== Phase 5: Testing & Documentation (4-6h) + +==== 5.1 Test Suite (2-3h) + +*Priority: HIGH* - Ensure reliability + +* [ ] *Unit tests* +** Parser tests (golden files) +** Analysis tests (vulnerability detection) +** Transform tests (before/after) +* [ ] *Integration tests* +** Full WordPress plugin analysis +** Real-world vulnerability detection +** Fix application verification +* [ ] *Property-based testing* +** Parser round-trip (parse → emit → parse) +** Transform idempotence + +==== 5.2 Documentation (2-3h) + +*Priority: MEDIUM* - User success + +* [ ] *User guide* +** Installation (Cabal, Stack, Nix, binaries) +** Quick start tutorial +** Configuration guide +** Workflow examples +* [ ] *Rule documentation* +** Security check reference +** Transform catalog +** WordPress-specific rules +* [ ] *API documentation* +** Haddock coverage +** Library usage examples +** Extension guide + +''''' + +=== Phase 6: Advanced Features (Optional, 4-6h) + +==== 6.1 Machine Learning Integration (2-3h) + +*Priority: LOW* - Cutting edge, experimental + +* [ ] *Pattern learning* +** Learn safe patterns from codebase +** Reduce false positives +** Suggest fixes based on codebase style +* [ ] *Anomaly detection* +** Find unusual code patterns +** Detect obfuscated malware + +==== 6.2 Plugin Ecosystem (2-3h) + +*Priority: LOW* - Extensibility + +* [ ] *Custom rule engine* +** DSL for defining custom checks +** Custom transformation passes +** Project-specific rules +* [ ] *Plugin architecture* +** Load external analysis modules +** Custom sanitizer definitions +** Framework-specific analyzers (Laravel, Symfony, etc.) + +''''' + +=== Summary: Path to 100% + +[cols=",,,",options="header",] +|=== +|Phase |Hours |Completion Gain |Target % +|Current |- |- |40% +|Phase 1: Core Completion |8-12 |+25% |65% +|Phase 2: Advanced Analysis |8-10 |+15% |80% +|Phase 3: Production CLI |6-8 |+10% |90% +|Phase 4: Advanced Transforms |6-8 |+5% |95% +|Phase 5: Testing & Docs |4-6 |+5% |100% +|*TOTAL* |*32-44h* |*+60%* |*100%* +|=== + +*Critical Path (to 80%):* 1. Complete Parser (4h) 2. Complete Emit (4h) +3. Complete Type Inference (3h) 4. Complete Taint Tracking (4h) 5. +WordPress Deep Analysis (3h) 6. Enhanced CLI (4h) 7. Automatic Fixes +(5h) + +*Total Critical Path: 27h* diff --git a/COMPREHENSIVE-ROADMAP.md b/COMPREHENSIVE-ROADMAP.md deleted file mode 100644 index c10ec57..0000000 --- a/COMPREHENSIVE-ROADMAP.md +++ /dev/null @@ -1,390 +0,0 @@ -# Sanctify-PHP Comprehensive Implementation Roadmap -**Target: 40% → 100% Completion** -**Vision: Production-Ready PHP Security Analysis & Hardening Tool** - -## Current Status Assessment (40%) - -### ✅ Implemented (Strong Foundation) -- **AST**: Comprehensive PHP 8.x AST with modern features (attributes, enums, match, etc.) -- **Parser**: Megaparsec-based PHP parser (basic structures working) -- **Security Analysis**: Extensive vulnerability detection - - SQL injection, XSS, CSRF, command injection - - Path traversal, unsafe deserialization - - Weak crypto (with modern recommendations: SHAKE3-256/BLAKE3) - - Hardcoded secrets detection - - Dangerous function flagging -- **Transform/Sanitize**: WordPress-specific security transformations - - Output escaping (esc_html, esc_attr, etc.) - - Input sanitization detection - - SQL preparation wrapping - - Superglobal sanitization - - Exit after redirect -- **WordPress**: WordPress-specific constraint checking -- **Core Modules**: Config, Report, Ruleset (exist but need verification) - -### ⚠️ Needs Completion/Enhancement (60% Gap) -1. **Parser**: Needs full PHP 8.x expression/statement coverage -2. **Emit**: PHP code generation from AST (critical for transformations) -3. **Taint Analysis**: Data flow tracking needs completion -4. **Type Inference**: PHP type system inference engine -5. **Dead Code**: Unused code detection -6. **CLI**: Production-ready command-line interface -7. **Testing**: Comprehensive test suite -8. **Documentation**: User guide, API docs, examples - ---- - -## Phase 1: Core Completion (8-12h) - CRITICAL - -### 1.1 Complete Parser (3-4h) ✅ COMPLETE -**Priority: CRITICAL** - Nothing works without a complete parser - -- [x] **Expression parsing completion** - - Match expressions (PHP 8.0) ✓ - - Null coalescing assignment (??=) ✓ - - Spread operator in arrays ✓ - - Arrow functions with attributes ✓ - - Ternary and elvis operators ✓ - - Method calls and property access (including nullsafe) ✓ - -- [x] **Statement parsing completion** - - Try/catch with multiple exception types ✓ - - Switch/match comprehensive coverage ✓ - - Declare directives (ticks, encoding) ✓ - - Global, static, unset statements ✓ - -- [x] **Modern PHP 8.x features** - - Readonly classes (PHP 8.2) ✓ - - DNF types (PHP 8.2) - `(A&B)|(C&D)` ✓ - - Constants in traits ✓ - - Attributes on all declarations ✓ - - Interface and enum parsing ✓ - - Constructor property promotion ✓ - -- [ ] **Robustness** (deferred to Phase 5) - - Better error recovery (don't fail on single parse error) - - Preserve whitespace/comments as metadata (for code generation) - - Line/column tracking for all nodes (partially done) - -### 1.2 Complete Emit - Code Generation (3-4h) ✅ COMPLETE -**Priority: CRITICAL** - Required for all transformations - -- [x] **Pretty printer from AST** - - Generate readable PHP code ✓ - - All statements (match, try/catch, declare, global, static, unset) ✓ - - All expressions (closures, arrow functions, yield, throw) ✓ - - All declarations (interface, trait, enum, functions, classes) ✓ - - Attributes on all declarations ✓ - - DNF types with proper parenthesization ✓ - - Constructor property promotion ✓ - -- [ ] **Transformation output** (deferred to Phase 4) - - Apply transform passes to AST - - Emit modified code - - Diff generation (show what changed) - -- [ ] **Code style enforcement** (deferred to Phase 4) - - PSR-12 compliance option - - WordPress coding standards option - - Configurable brace style, spacing - -### 1.3 Type Inference Completion (2-3h) -**Priority: HIGH** - Enables automatic type hint addition - -- [ ] **Basic type inference** - - Infer return types from function bodies - - Infer parameter types from usage - - Propagate types through assignments - -- [ ] **WordPress type inference** - - Recognize WordPress function signatures - - Hook parameter type inference - - WP_Query, WP_Post type awareness - -- [ ] **Generics awareness** - - array inference - - Collection type tracking - ---- - -## Phase 2: Advanced Analysis (8-10h) - -### 2.1 Complete Taint Tracking (3-4h) -**Priority: HIGH** - Critical for security analysis accuracy - -- [ ] **Data flow graph** - - Build control flow graph - - Track tainted data propagation - - Source → Sink analysis - -- [ ] **Taint sources** - - Superglobals ($_GET, $_POST, $_COOKIE, etc.) - - Database query results (trust context) - - User input functions (file_get_contents, etc.) - -- [ ] **Sanitizers recognition** - - WordPress sanitization functions - - PHP filter functions - - Custom sanitizer patterns - -- [ ] **Sinks** - - SQL queries, shell commands - - File operations, eval - - Output (echo, print) - -### 2.2 WordPress-Specific Deep Analysis (2-3h) -**Priority: MEDIUM** - Differentiator for WP developers - -- [ ] **Hook analysis** - - Detect priority conflicts - - Find missing/misplaced hooks - - Identify wrong hook usage - -- [ ] **Capability checking** - - Find missing current_user_can() checks - - Detect privilege escalation risks - - Admin vs frontend context - -- [ ] **Nonce verification** - - Comprehensive CSRF detection - - Find form submissions without nonces - - AJAX handler nonce checking - -- [ ] **Database query analysis** - - $wpdb->prepare() compliance - - Direct SQL detection - - Table prefix usage - -- [ ] **Internationalization** - - Find untranslated strings - - Detect missing text domains - - Check escaping+translation combos - -### 2.3 Advanced Security Checks (3-4h) -**Priority: HIGH** - Beyond basic OWASP - -- [ ] **Time-of-check-time-of-use (TOCTOU)** - - File operation race conditions - - Permission check bypasses - -- [ ] **Regular expression DoS (ReDoS)** - - Detect catastrophic backtracking patterns - - Flag unsafe regex in preg_* functions - -- [ ] **Server-Side Request Forgery (SSRF)** - - wp_remote_get/post with user input - - file_get_contents with URLs - -- [ ] **XML External Entity (XXE)** - - simplexml_load_* without disable_entity_loader - - DOMDocument loadXML safety - -- [ ] **Insecure direct object references** - - Missing ownership checks on database queries - - User ID manipulation detection - -- [ ] **Mass assignment vulnerabilities** - - Unvalidated array assignments to models - ---- - -## Phase 3: Production CLI & Tooling (6-8h) - -### 3.1 Enhanced CLI (3-4h) ✅ COMPLETE -**Priority: HIGH** - User-facing interface - -- [x] **Command improvements** - - `sanctify analyze` - full analysis with report ✓ - - `sanctify fix --interactive` - interactive fixing with previews ✓ - - `sanctify fix --diff` - show unified diff of changes ✓ - - `sanctify --watch` - watch mode for development ✓ - -- [x] **Output formats** - - JSON (machine-readable) ✓ - - SARIF (GitHub/GitLab integration) ✓ - - HTML (rich visualization) ✓ - - Terminal (text output) ✓ - -- [x] **Filtering & targeting** - - `--severity=high,critical` - filter by severity ✓ - - `--type=sql,xss` - filter by vulnerability type ✓ - - `--in-place` - apply fixes to files ✓ - - `--verbose` - detailed output ✓ - -- [ ] **Performance** (deferred to Phase 6) - - Parallel file processing - - Incremental analysis (only changed files) - - Result caching - - `.sanctifyignore` support - -### 3.2 Integration & Export (2-3h) -**Priority: MEDIUM** - DevOps integration - -- [ ] **CI/CD integration** - - Exit codes for CI failure - - GitHub Actions integration - - GitLab CI templates - - Pre-commit hooks - -- [ ] **IDE integration preparation** - - Language Server Protocol (LSP) foundations - - JSON-RPC interface - - Real-time analysis hooks - -- [ ] **Configuration export** - - php.ini hardening recommendations - - nginx/Apache security headers - - Guix/Nix package definitions - - Docker security options - -### 3.3 Reporting & Metrics (1-2h) -**Priority: MEDIUM** - Visibility and tracking - -- [ ] **Comprehensive reports** - - Executive summary - - Trend analysis (compare with previous scans) - - Remediation guidance with code examples - - Risk scoring - -- [ ] **Metrics & dashboards** - - Security score calculation - - Issue distribution (by type, severity, file) - - Fix effort estimation - - Progress tracking - ---- - -## Phase 4: Advanced Transformations (6-8h) - -### 4.1 Automatic Fixes (4-5h) -**Priority: HIGH** - Save developer time - -- [ ] **Safe auto-fixes** (zero-risk, always apply) - - Add `declare(strict_types=1)` - - Add ABSPATH check to WP files - - Convert `rand()` → `random_int()` - - Add `exit` after `wp_redirect()` - - Fix missing text domains in i18n functions - -- [ ] **Semi-automatic fixes** (suggest with preview) - - Wrap superglobals with sanitizers - - Replace `$wpdb->query()` with `$wpdb->prepare()` - - Add nonce verification scaffolding - - Wrap `echo` with `esc_html()` - -- [ ] **Type hint addition** - - Infer and add parameter types - - Infer and add return types - - Add property types - -- [ ] **Modernization** - - Convert old array() → [] - - Convert isset() chains → null coalescing - - Convert create_function() → closures - -### 4.2 Code Quality Transformations (2-3h) -**Priority: MEDIUM** - Beyond security - -- [ ] **PSR compliance** - - Naming conventions - - File organization - - Docblock generation - -- [ ] **WordPress standards** - - Yoda conditions - - Brace style - - Hook documentation - ---- - -## Phase 5: Testing & Documentation (4-6h) - -### 5.1 Test Suite (2-3h) -**Priority: HIGH** - Ensure reliability - -- [ ] **Unit tests** - - Parser tests (golden files) - - Analysis tests (vulnerability detection) - - Transform tests (before/after) - -- [ ] **Integration tests** - - Full WordPress plugin analysis - - Real-world vulnerability detection - - Fix application verification - -- [ ] **Property-based testing** - - Parser round-trip (parse → emit → parse) - - Transform idempotence - -### 5.2 Documentation (2-3h) -**Priority: MEDIUM** - User success - -- [ ] **User guide** - - Installation (Cabal, Stack, Nix, binaries) - - Quick start tutorial - - Configuration guide - - Workflow examples - -- [ ] **Rule documentation** - - Security check reference - - Transform catalog - - WordPress-specific rules - -- [ ] **API documentation** - - Haddock coverage - - Library usage examples - - Extension guide - ---- - -## Phase 6: Advanced Features (Optional, 4-6h) - -### 6.1 Machine Learning Integration (2-3h) -**Priority: LOW** - Cutting edge, experimental - -- [ ] **Pattern learning** - - Learn safe patterns from codebase - - Reduce false positives - - Suggest fixes based on codebase style - -- [ ] **Anomaly detection** - - Find unusual code patterns - - Detect obfuscated malware - -### 6.2 Plugin Ecosystem (2-3h) -**Priority: LOW** - Extensibility - -- [ ] **Custom rule engine** - - DSL for defining custom checks - - Custom transformation passes - - Project-specific rules - -- [ ] **Plugin architecture** - - Load external analysis modules - - Custom sanitizer definitions - - Framework-specific analyzers (Laravel, Symfony, etc.) - ---- - -## Summary: Path to 100% - -| Phase | Hours | Completion Gain | Target % | -|-------|-------|-----------------|----------| -| Current | - | - | 40% | -| Phase 1: Core Completion | 8-12 | +25% | 65% | -| Phase 2: Advanced Analysis | 8-10 | +15% | 80% | -| Phase 3: Production CLI | 6-8 | +10% | 90% | -| Phase 4: Advanced Transforms | 6-8 | +5% | 95% | -| Phase 5: Testing & Docs | 4-6 | +5% | 100% | -| **TOTAL** | **32-44h** | **+60%** | **100%** | - -**Critical Path (to 80%):** -1. Complete Parser (4h) -2. Complete Emit (4h) -3. Complete Type Inference (3h) -4. Complete Taint Tracking (4h) -5. WordPress Deep Analysis (3h) -6. Enhanced CLI (4h) -7. Automatic Fixes (5h) - -**Total Critical Path: 27h** diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc new file mode 100644 index 0000000..23ce71c --- /dev/null +++ b/CONTRIBUTING.adoc @@ -0,0 +1,109 @@ +== Clone the repository + +git clone https://github.com/hyperpolymath/sanctify-php.git cd +sanctify-php + +== Using Nix (recommended for reproducibility) + +nix develop + +== Or using toolbox/distrobox + +toolbox create sanctify-php-dev toolbox enter sanctify-php-dev # Install +dependencies manually + +== Verify setup + +just check # or: cargo check / mix compile / etc. just test # Run test +suite + +.... + +### Repository Structure +.... + +sanctify-php/ ├── src/ # Source code (Perimeter 1-2) ├── lib/ # Library +code (Perimeter 1-2) ├── extensions/ # Extensions (Perimeter 2) ├── +plugins/ # Plugins (Perimeter 2) ├── tools/ # Tooling (Perimeter 2) ├── +docs/ # Documentation (Perimeter 3) │ ├── architecture/ # ADRs, specs +(Perimeter 2) │ └── proposals/ # RFCs (Perimeter 3) ├── examples/ # +Examples (Perimeter 3) ├── spec/ # Spec tests (Perimeter 3) ├── tests/ # +Test suite (Perimeter 2-3) ├── .well-known/ # Protocol files (Perimeter +1-3) ├── .github/ # GitHub config (Perimeter 1) │ ├── ISSUE_TEMPLATE/ │ +└── workflows/ ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── +CONTRIBUTING.md # This file ├── GOVERNANCE.md ├── LICENSE ├── +MAINTAINERS.md ├── README.adoc ├── SECURITY.md ├── flake.nix # Nix flake +(Perimeter 1) └── Justfile # Task runner (Perimeter 1) + +.... + +--- + +## How to Contribute + +### Reporting Bugs + +**Before reporting**: +1. Search existing issues +2. Check if it's already fixed in `main` +3. Determine which perimeter the bug affects + +**When reporting**: + +Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: + +- Clear, descriptive title +- Environment details (OS, versions, toolchain) +- Steps to reproduce +- Expected vs actual behaviour +- Logs, screenshots, or minimal reproduction + +### Suggesting Features + +**Before suggesting**: +1. Check the [roadmap](ROADMAP.md) if available +2. Search existing issues and discussions +3. Consider which perimeter the feature belongs to + +**When suggesting**: + +Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: + +- Problem statement (what pain point does this solve?) +- Proposed solution +- Alternatives considered +- Which perimeter this affects + +### Your First Contribution + +Look for issues labelled: + +- [`good first issue`](https://github.com/hyperpolymath/sanctify-php/labels/good%20first%20issue) — Simple Perimeter 3 tasks +- [`help wanted`](https://github.com/hyperpolymath/sanctify-php/labels/help%20wanted) — Community help needed +- [`documentation`](https://github.com/hyperpolymath/sanctify-php/labels/documentation) — Docs improvements +- [`perimeter-3`](https://github.com/hyperpolymath/sanctify-php/labels/perimeter-3) — Community sandbox scope + +--- + +## Development Workflow + +### Branch Naming +.... + +docs/short-description # Documentation (P3) test/what-added # Test +additions (P3) feat/short-description # New features (P2) +fix/issue-number-description # Bug fixes (P2) refactor/what-changed # +Code improvements (P2) security/what-fixed # Security fixes (P1-2) + +.... + +### Commit Messages + +We follow [Conventional Commits](https://www.conventionalcommits.org/): +.... + +(): + +{empty}[optional body] + +{empty}[optional footer] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 77b8be9..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,116 +0,0 @@ -# Clone the repository -git clone https://github.com/hyperpolymath/sanctify-php.git -cd sanctify-php - -# Using Nix (recommended for reproducibility) -nix develop - -# Or using toolbox/distrobox -toolbox create sanctify-php-dev -toolbox enter sanctify-php-dev -# Install dependencies manually - -# Verify setup -just check # or: cargo check / mix compile / etc. -just test # Run test suite -``` - -### Repository Structure -``` -sanctify-php/ -├── src/ # Source code (Perimeter 1-2) -├── lib/ # Library code (Perimeter 1-2) -├── extensions/ # Extensions (Perimeter 2) -├── plugins/ # Plugins (Perimeter 2) -├── tools/ # Tooling (Perimeter 2) -├── docs/ # Documentation (Perimeter 3) -│ ├── architecture/ # ADRs, specs (Perimeter 2) -│ └── proposals/ # RFCs (Perimeter 3) -├── examples/ # Examples (Perimeter 3) -├── spec/ # Spec tests (Perimeter 3) -├── tests/ # Test suite (Perimeter 2-3) -├── .well-known/ # Protocol files (Perimeter 1-3) -├── .github/ # GitHub config (Perimeter 1) -│ ├── ISSUE_TEMPLATE/ -│ └── workflows/ -├── CHANGELOG.md -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md # This file -├── GOVERNANCE.md -├── LICENSE -├── MAINTAINERS.md -├── README.adoc -├── SECURITY.md -├── flake.nix # Nix flake (Perimeter 1) -└── Justfile # Task runner (Perimeter 1) -``` - ---- - -## How to Contribute - -### Reporting Bugs - -**Before reporting**: -1. Search existing issues -2. Check if it's already fixed in `main` -3. Determine which perimeter the bug affects - -**When reporting**: - -Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: - -- Clear, descriptive title -- Environment details (OS, versions, toolchain) -- Steps to reproduce -- Expected vs actual behaviour -- Logs, screenshots, or minimal reproduction - -### Suggesting Features - -**Before suggesting**: -1. Check the [roadmap](ROADMAP.md) if available -2. Search existing issues and discussions -3. Consider which perimeter the feature belongs to - -**When suggesting**: - -Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: - -- Problem statement (what pain point does this solve?) -- Proposed solution -- Alternatives considered -- Which perimeter this affects - -### Your First Contribution - -Look for issues labelled: - -- [`good first issue`](https://github.com/hyperpolymath/sanctify-php/labels/good%20first%20issue) — Simple Perimeter 3 tasks -- [`help wanted`](https://github.com/hyperpolymath/sanctify-php/labels/help%20wanted) — Community help needed -- [`documentation`](https://github.com/hyperpolymath/sanctify-php/labels/documentation) — Docs improvements -- [`perimeter-3`](https://github.com/hyperpolymath/sanctify-php/labels/perimeter-3) — Community sandbox scope - ---- - -## Development Workflow - -### Branch Naming -``` -docs/short-description # Documentation (P3) -test/what-added # Test additions (P3) -feat/short-description # New features (P2) -fix/issue-number-description # Bug fixes (P2) -refactor/what-changed # Code improvements (P2) -security/what-fixed # Security fixes (P1-2) -``` - -### Commit Messages - -We follow [Conventional Commits](https://www.conventionalcommits.org/): -``` -(): - -[optional body] - -[optional footer] 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/PROGRESS-SUMMARY.adoc b/PROGRESS-SUMMARY.adoc new file mode 100644 index 0000000..825be84 --- /dev/null +++ b/PROGRESS-SUMMARY.adoc @@ -0,0 +1,292 @@ +== Sanctify-PHP Development Progress Summary + +=== Overall Status: 93% Complete + +*Project Phase*: Production Ready - Comprehensive Security Tool + +From initial 40% → *93% complete* (53 percentage points gained) + +''''' + +=== ✅ Completed Components (100%) + +==== Core Infrastructure + +* *AST (100%)*: Comprehensive PHP 8.x AST with all modern features +* *Parser (100%)*: Complete PHP 8.2+ parser +** Readonly classes (`+readonly class User+`) +** DNF types (`+(A&B)|(C&D)+`) +** Enums (pure and backed) +** Attributes on all declarations +** Match expressions +** Constructor property promotion +** Traits with constants +** Interfaces and enums +** Arrow functions, closures +** Null coalescing assignment (`+??=+`) +** Nullsafe operators (`+?->+`) +* *Emit (100%)*: Complete code generation +** All statements (match, closures, arrow functions, global, static, +unset, declare) +** All expressions (yield, throw, class const access) +** All declarations (interface, trait, enum with attributes) +** DNF type parenthesization +** Constructor promotion emission +* *CLI (100%)*: Production-ready command-line interface +** Interactive fix mode with y/N/d/s prompts +** Watch mode for live re-analysis +** Multiple output formats (text, JSON, SARIF, HTML) +** Severity filtering (critical, high, medium, low, info) +** Type filtering (by vulnerability type) +** Unified diff preview +** In-place modification +** Verbose mode + +==== Security Analysis + +* *Basic Security (95%)*: OWASP Top 10 coverage +** SQL injection (with WordPress $wpdb awareness) +** XSS (with WordPress escaping functions) +** CSRF/nonce verification +** Command injection +** Path traversal +** Unsafe deserialization +** Weak crypto (with SHAKE3-256/BLAKE3 recommendations) +** Hardcoded secrets +** Dangerous functions +* *Advanced Security (100%)*: Modern threat detection +** ReDoS (catastrophic backtracking patterns) +** SSRF (server-side request forgery) +** XXE (XML external entity injection) +** TOCTOU (time-of-check-time-of-use) +** Timing attacks +** Object injection +** Mass assignment +* *WordPress Security (100%)*: Deep WordPress analysis +** Nonce verification (forms, AJAX, REST API) +** Capability checks (all privilege levels) +** AJAX security (nonce + capability) +** REST API security (permission callbacks) +** File upload security +** Transient security +** Cron job security +** Gutenberg block security +** i18n security + +==== Testing + +* *Test Suite (85%)*: +** ParserSpec: PHP 8.2+ parsing, round-trip tests, error recovery +** SecuritySpec: All vulnerability types with detection validation +** TransformSpec: All transformations with idempotence checks +** Test fixtures: 5 comprehensive PHP files (vulnerable and safe +examples) +** Cabal test configuration with hspec-discover + +==== Documentation + +* *User Documentation (95%)*: +** QUICKSTART.adoc: Installation, basic usage, workflows, examples +** USER-GUIDE.adoc Part 1: Commands, configuration, vulnerability +reference +** USER-GUIDE-PART2.adoc: Advanced features, WordPress patterns, CI/CD +* *Developer Documentation (95%)*: +** ARCHITECTURE.adoc: Module structure, AST design, parser, emit, +analysis +** EXTENDING.adoc: Custom checks, transforms, plugins, testing, +contributing +* *API Documentation (95%)*: +** API-REFERENCE.adoc: Complete API with types, functions, examples +* *Documentation Index*: +** docs/README.adoc: Navigation, quick reference, task-based guide + +''''' + +=== 🚧 In Progress (70-90%) + +==== Transformations + +* *Transform Sanitize (90%)*: Output escaping, input sanitization, SQL +preparation +* *Transform Strict (85%)*: Strict types, ABSPATH checks +* *Transform TypeHints (80%)*: Type hint addition and inference + +==== Analysis + +* *Type Inference (75%)*: Type inference for PHP code +* *Taint Tracking (70%)*: Taint tracking for data flow +* *Dead Code (65%)*: Unused code detection + +==== Configuration + +* *Config (90%)*: Configuration loading and validation +* *Report (85%)*: JSON, SARIF, HTML report generation +* *WordPress Constraints (85%)*: WP-specific patterns + +''''' + +=== ⏳ Remaining Work (7% to reach 100%) + +==== Critical Path to v1.0 + +[arabic] +. *Complete Type Inference (75% → 100%)* +* Infer return types from function bodies +* Propagate types through assignments +* WordPress function signature awareness +* Generic type inference (array) +. *Complete Taint Tracking (70% → 100%)* +* Build control flow graph +* Track tainted data propagation +* Source → Sink analysis +* Custom sanitizer recognition +. *Finalize Dead Code Detection (65% → 100%)* +* Unused variable detection +* Unreachable code detection +* Unused function/class detection +. *Real-World Testing* +* Test against popular WordPress plugins +* Validate detection accuracy +* Collect false positive/negative data +* Fine-tune analysis rules +. *CI/CD Templates* +* GitHub Actions workflow +* GitLab CI template +* Pre-commit hook template +* Jenkins pipeline +. *Performance Optimization* +* Parallel file processing +* Incremental analysis +* Result caching +* `+.sanctifyignore+` support + +''''' + +=== 📊 Session Breakdown + +==== Session 2026-01-23a (40% → 75%) + +* Created advanced security analysis (13 new checks) +* Created WordPress deep security analysis (16 new checks) +* Created comprehensive roadmap + +==== Session 2026-01-23b (75% → 82%) + +* Parser completion: readonly classes, DNF types, traits, enums, +attributes +* Enhanced expression/statement parsing +* Added postfix operators + +==== Session 2026-01-23c (82% → 84%) + +* Emit completion: match, closures, arrow functions +* Interface/trait/enum emission +* Attribute emission, DNF type handling + +==== Session 2026-01-23d (84% → 87%) + +* CLI enhancement: interactive mode, watch mode +* Multiple output formats +* Advanced filtering and diff preview + +==== Session 2026-01-23e (87% → 90%) + +* Comprehensive test suite creation +* Test fixtures (5 files) +* Quick-start deployment guide +* Cabal configuration + +==== Session 2026-01-23f (90% → 93%) + +* Complete wiki documentation +* User guide (2 parts, 40+ pages) +* Architecture guide +* Extension guide +* API reference + +''''' + +=== 🎯 Milestone Status + +==== ✅ v0.1 Foundation (COMPLETE) + +* Core AST design +* Basic parser implementation +* OWASP Top 10 security checks +* WordPress constraint checking +* Basic transformations + +==== 🚧 v0.2 Advanced (NEAR COMPLETE - 93%) + +* ✅ Advanced security analysis module +* ✅ WordPress deep security analysis +* ✅ Complete parser for PHP 8.2+ +* ✅ Enhanced CLI with interactive mode +* ✅ Comprehensive test suite +* ✅ Production documentation + +==== ⏳ v0.3 Production (PENDING) + +* LSP server for IDE integration +* Incremental analysis +* CI/CD integration templates +* Plugin architecture + +''''' + +=== 🔥 Key Achievements + +[arabic] +. *Most Complete PHP 8.2+ Parser in Haskell* +* Full support for readonly classes, DNF types, enums, attributes +* Megaparsec-based with excellent error messages +. *WordPress-Native Security Tool* +* Only tool with deep WordPress understanding +* Detects nonce, capability, AJAX, REST API issues +. *Advanced Threat Detection* +* ReDoS, SSRF, XXE, TOCTOU beyond basic OWASP +* Timing attack and object injection detection +. *Production-Ready CLI* +* Interactive fix mode unique among PHP tools +* Watch mode for development workflow +* SARIF output for CI/CD integration +. *Comprehensive Documentation* +* 60+ pages of user documentation +* Complete developer architecture guide +* Full API reference with examples + +''''' + +=== 📝 Next Steps + +[arabic] +. *Test Against Real Plugins* (Priority: HIGH) +* WooCommerce +* Yoast SEO +* Contact Form 7 +* Validate accuracy and find edge cases +. *Complete Type Inference* (Priority: MEDIUM) +* Finish inference engine +* Add WordPress function signatures +. *Complete Taint Tracking* (Priority: MEDIUM) +* Build CFG +* Implement data flow analysis +. *CI/CD Integration* (Priority: LOW) +* Create workflow templates +* Write integration guide + +''''' + +=== 🎉 Summary + +Sanctify-PHP has gone from 40% to *93% complete* in this development +session. It is now: + +✅ *Feature-complete* for security analysis ✅ *Production-ready* CLI +interface ✅ *Fully documented* for users and developers ✅ +*Comprehensively tested* with unit/integration tests + +*Ready for*: Alpha/beta testing with real WordPress projects + +*Remaining*: Fine-tuning, performance optimization, real-world +validation diff --git a/PROGRESS-SUMMARY.md b/PROGRESS-SUMMARY.md deleted file mode 100644 index 2333be7..0000000 --- a/PROGRESS-SUMMARY.md +++ /dev/null @@ -1,276 +0,0 @@ -# Sanctify-PHP Development Progress Summary - -## Overall Status: 93% Complete - -**Project Phase**: Production Ready - Comprehensive Security Tool - -From initial 40% → **93% complete** (53 percentage points gained) - ---- - -## ✅ Completed Components (100%) - -### Core Infrastructure -- **AST (100%)**: Comprehensive PHP 8.x AST with all modern features -- **Parser (100%)**: Complete PHP 8.2+ parser - - Readonly classes (`readonly class User`) - - DNF types (`(A&B)|(C&D)`) - - Enums (pure and backed) - - Attributes on all declarations - - Match expressions - - Constructor property promotion - - Traits with constants - - Interfaces and enums - - Arrow functions, closures - - Null coalescing assignment (`??=`) - - Nullsafe operators (`?->`) -- **Emit (100%)**: Complete code generation - - All statements (match, closures, arrow functions, global, static, unset, declare) - - All expressions (yield, throw, class const access) - - All declarations (interface, trait, enum with attributes) - - DNF type parenthesization - - Constructor promotion emission -- **CLI (100%)**: Production-ready command-line interface - - Interactive fix mode with y/N/d/s prompts - - Watch mode for live re-analysis - - Multiple output formats (text, JSON, SARIF, HTML) - - Severity filtering (critical, high, medium, low, info) - - Type filtering (by vulnerability type) - - Unified diff preview - - In-place modification - - Verbose mode - -### Security Analysis -- **Basic Security (95%)**: OWASP Top 10 coverage - - SQL injection (with WordPress $wpdb awareness) - - XSS (with WordPress escaping functions) - - CSRF/nonce verification - - Command injection - - Path traversal - - Unsafe deserialization - - Weak crypto (with SHAKE3-256/BLAKE3 recommendations) - - Hardcoded secrets - - Dangerous functions -- **Advanced Security (100%)**: Modern threat detection - - ReDoS (catastrophic backtracking patterns) - - SSRF (server-side request forgery) - - XXE (XML external entity injection) - - TOCTOU (time-of-check-time-of-use) - - Timing attacks - - Object injection - - Mass assignment -- **WordPress Security (100%)**: Deep WordPress analysis - - Nonce verification (forms, AJAX, REST API) - - Capability checks (all privilege levels) - - AJAX security (nonce + capability) - - REST API security (permission callbacks) - - File upload security - - Transient security - - Cron job security - - Gutenberg block security - - i18n security - -### Testing -- **Test Suite (85%)**: - - ParserSpec: PHP 8.2+ parsing, round-trip tests, error recovery - - SecuritySpec: All vulnerability types with detection validation - - TransformSpec: All transformations with idempotence checks - - Test fixtures: 5 comprehensive PHP files (vulnerable and safe examples) - - Cabal test configuration with hspec-discover - -### Documentation -- **User Documentation (95%)**: - - QUICKSTART.adoc: Installation, basic usage, workflows, examples - - USER-GUIDE.adoc Part 1: Commands, configuration, vulnerability reference - - USER-GUIDE-PART2.adoc: Advanced features, WordPress patterns, CI/CD -- **Developer Documentation (95%)**: - - ARCHITECTURE.adoc: Module structure, AST design, parser, emit, analysis - - EXTENDING.adoc: Custom checks, transforms, plugins, testing, contributing -- **API Documentation (95%)**: - - API-REFERENCE.adoc: Complete API with types, functions, examples -- **Documentation Index**: - - docs/README.adoc: Navigation, quick reference, task-based guide - ---- - -## 🚧 In Progress (70-90%) - -### Transformations -- **Transform Sanitize (90%)**: Output escaping, input sanitization, SQL preparation -- **Transform Strict (85%)**: Strict types, ABSPATH checks -- **Transform TypeHints (80%)**: Type hint addition and inference - -### Analysis -- **Type Inference (75%)**: Type inference for PHP code -- **Taint Tracking (70%)**: Taint tracking for data flow -- **Dead Code (65%)**: Unused code detection - -### Configuration -- **Config (90%)**: Configuration loading and validation -- **Report (85%)**: JSON, SARIF, HTML report generation -- **WordPress Constraints (85%)**: WP-specific patterns - ---- - -## ⏳ Remaining Work (7% to reach 100%) - -### Critical Path to v1.0 -1. **Complete Type Inference (75% → 100%)** - - Infer return types from function bodies - - Propagate types through assignments - - WordPress function signature awareness - - Generic type inference (array) - -2. **Complete Taint Tracking (70% → 100%)** - - Build control flow graph - - Track tainted data propagation - - Source → Sink analysis - - Custom sanitizer recognition - -3. **Finalize Dead Code Detection (65% → 100%)** - - Unused variable detection - - Unreachable code detection - - Unused function/class detection - -4. **Real-World Testing** - - Test against popular WordPress plugins - - Validate detection accuracy - - Collect false positive/negative data - - Fine-tune analysis rules - -5. **CI/CD Templates** - - GitHub Actions workflow - - GitLab CI template - - Pre-commit hook template - - Jenkins pipeline - -6. **Performance Optimization** - - Parallel file processing - - Incremental analysis - - Result caching - - `.sanctifyignore` support - ---- - -## 📊 Session Breakdown - -### Session 2026-01-23a (40% → 75%) -- Created advanced security analysis (13 new checks) -- Created WordPress deep security analysis (16 new checks) -- Created comprehensive roadmap - -### Session 2026-01-23b (75% → 82%) -- Parser completion: readonly classes, DNF types, traits, enums, attributes -- Enhanced expression/statement parsing -- Added postfix operators - -### Session 2026-01-23c (82% → 84%) -- Emit completion: match, closures, arrow functions -- Interface/trait/enum emission -- Attribute emission, DNF type handling - -### Session 2026-01-23d (84% → 87%) -- CLI enhancement: interactive mode, watch mode -- Multiple output formats -- Advanced filtering and diff preview - -### Session 2026-01-23e (87% → 90%) -- Comprehensive test suite creation -- Test fixtures (5 files) -- Quick-start deployment guide -- Cabal configuration - -### Session 2026-01-23f (90% → 93%) -- Complete wiki documentation -- User guide (2 parts, 40+ pages) -- Architecture guide -- Extension guide -- API reference - ---- - -## 🎯 Milestone Status - -### ✅ v0.1 Foundation (COMPLETE) -- Core AST design -- Basic parser implementation -- OWASP Top 10 security checks -- WordPress constraint checking -- Basic transformations - -### 🚧 v0.2 Advanced (NEAR COMPLETE - 93%) -- ✅ Advanced security analysis module -- ✅ WordPress deep security analysis -- ✅ Complete parser for PHP 8.2+ -- ✅ Enhanced CLI with interactive mode -- ✅ Comprehensive test suite -- ✅ Production documentation - -### ⏳ v0.3 Production (PENDING) -- LSP server for IDE integration -- Incremental analysis -- CI/CD integration templates -- Plugin architecture - ---- - -## 🔥 Key Achievements - -1. **Most Complete PHP 8.2+ Parser in Haskell** - - Full support for readonly classes, DNF types, enums, attributes - - Megaparsec-based with excellent error messages - -2. **WordPress-Native Security Tool** - - Only tool with deep WordPress understanding - - Detects nonce, capability, AJAX, REST API issues - -3. **Advanced Threat Detection** - - ReDoS, SSRF, XXE, TOCTOU beyond basic OWASP - - Timing attack and object injection detection - -4. **Production-Ready CLI** - - Interactive fix mode unique among PHP tools - - Watch mode for development workflow - - SARIF output for CI/CD integration - -5. **Comprehensive Documentation** - - 60+ pages of user documentation - - Complete developer architecture guide - - Full API reference with examples - ---- - -## 📝 Next Steps - -1. **Test Against Real Plugins** (Priority: HIGH) - - WooCommerce - - Yoast SEO - - Contact Form 7 - - Validate accuracy and find edge cases - -2. **Complete Type Inference** (Priority: MEDIUM) - - Finish inference engine - - Add WordPress function signatures - -3. **Complete Taint Tracking** (Priority: MEDIUM) - - Build CFG - - Implement data flow analysis - -4. **CI/CD Integration** (Priority: LOW) - - Create workflow templates - - Write integration guide - ---- - -## 🎉 Summary - -Sanctify-PHP has gone from 40% to **93% complete** in this development session. It is now: - -✅ **Feature-complete** for security analysis -✅ **Production-ready** CLI interface -✅ **Fully documented** for users and developers -✅ **Comprehensively tested** with unit/integration tests - -**Ready for**: Alpha/beta testing with real WordPress projects - -**Remaining**: Fine-tuning, performance optimization, real-world validation diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc new file mode 100644 index 0000000..bfd9c81 --- /dev/null +++ b/PROOF-NEEDS.adoc @@ -0,0 +1,63 @@ +== PROOF-NEEDS.md + +=== Current State + +* *LOC*: ~9,400 +* *Languages*: Haskell, Idris2, Zig +* *Existing ABI proofs*: `+src/abi/*.idr+` (template-level) +* *Dangerous patterns*: None detected in Haskell source + +=== What Needs Proving + +==== Taint Analysis (src/Sanctify/Analysis/Taint.hs) + +* Tracks tainted data flow through PHP code +* Prove: taint propagation is sound (no tainted value reaches a sink +without sanitization) +* This is the security-critical core of the tool + +==== Security Analysis (src/Sanctify/Analysis/Security.hs) + +* Detects security vulnerabilities in PHP +* Prove: analysis does not have false negatives for the declared +vulnerability classes + +==== Dead Code Analysis (src/Sanctify/Analysis/DeadCode.hs) + +* Prove: reported dead code is genuinely unreachable + +==== Type Checker (src/Sanctify/Analysis/Types.hs) + +* PHP type inference +* Prove: type inference is sound with respect to PHP runtime semantics + +==== Parser Correctness (src/Sanctify/Parser/) + +* `+Parser.hs+`, `+Lexer.hs+`, `+Token.hs+` +* Prove: parser accepts valid PHP and rejects invalid PHP (or at +minimum, is conservative) + +==== Transform Soundness (src/Sanctify/Transform/) + +* `+Sanitize.hs+`, `+Strict.hs+`, `+StrictTypes.hs+`, `+TypeHints.hs+` +* Prove: code transformations preserve program semantics +* Prove: sanitization transforms eliminate the security vulnerabilities +they claim to fix + +==== WordPress-Specific Rules (src/Sanctify/WordPress/) + +* `+Constraints.hs+`, `+Hooks.hs+`, `+Security.hs+` +* Prove: WordPress hook analysis correctly models WordPress execution +order + +=== Recommended Prover + +* *Agda* or *Lean4* — Haskell analysis tools have a strong tradition of +formal verification +* *Idris2* for ABI contracts + +=== Priority + +*HIGH* — Security analysis tool. If the taint analysis is unsound, users +trust code that is actually vulnerable. False negatives in a security +tool are worse than no tool at all. diff --git a/PROOF-NEEDS.md b/PROOF-NEEDS.md deleted file mode 100644 index 3d50e55..0000000 --- a/PROOF-NEEDS.md +++ /dev/null @@ -1,49 +0,0 @@ -# PROOF-NEEDS.md - - -## Current State - -- **LOC**: ~9,400 -- **Languages**: Haskell, Idris2, Zig -- **Existing ABI proofs**: `src/abi/*.idr` (template-level) -- **Dangerous patterns**: None detected in Haskell source - -## What Needs Proving - -### Taint Analysis (src/Sanctify/Analysis/Taint.hs) -- Tracks tainted data flow through PHP code -- Prove: taint propagation is sound (no tainted value reaches a sink without sanitization) -- This is the security-critical core of the tool - -### Security Analysis (src/Sanctify/Analysis/Security.hs) -- Detects security vulnerabilities in PHP -- Prove: analysis does not have false negatives for the declared vulnerability classes - -### Dead Code Analysis (src/Sanctify/Analysis/DeadCode.hs) -- Prove: reported dead code is genuinely unreachable - -### Type Checker (src/Sanctify/Analysis/Types.hs) -- PHP type inference -- Prove: type inference is sound with respect to PHP runtime semantics - -### Parser Correctness (src/Sanctify/Parser/) -- `Parser.hs`, `Lexer.hs`, `Token.hs` -- Prove: parser accepts valid PHP and rejects invalid PHP (or at minimum, is conservative) - -### Transform Soundness (src/Sanctify/Transform/) -- `Sanitize.hs`, `Strict.hs`, `StrictTypes.hs`, `TypeHints.hs` -- Prove: code transformations preserve program semantics -- Prove: sanitization transforms eliminate the security vulnerabilities they claim to fix - -### WordPress-Specific Rules (src/Sanctify/WordPress/) -- `Constraints.hs`, `Hooks.hs`, `Security.hs` -- Prove: WordPress hook analysis correctly models WordPress execution order - -## Recommended Prover - -- **Agda** or **Lean4** — Haskell analysis tools have a strong tradition of formal verification -- **Idris2** for ABI contracts - -## Priority - -**HIGH** — Security analysis tool. If the taint analysis is unsound, users trust code that is actually vulnerable. False negatives in a security tool are worse than no tool at all. diff --git a/SECURITY.md b/SECURITY.adoc similarity index 52% rename from SECURITY.md rename to SECURITY.adoc index 034e848..1288150 100644 --- a/SECURITY.md +++ b/SECURITY.adoc @@ -1,21 +1,23 @@ -# Security Policy +== Security Policy -## Supported Versions +=== Supported Versions Use this section to tell people about which versions of your project are currently being supported with security updates. -| Version | Supported | -| ------- | ------------------ | -| 5.1.x | :white_check_mark: | -| 5.0.x | :x: | -| 4.0.x | :white_check_mark: | -| < 4.0 | :x: | +[cols=",",options="header",] +|=== +|Version |Supported +|5.1.x |:white_check_mark: +|5.0.x |:x: +|4.0.x |:white_check_mark: +|< 4.0 |:x: +|=== -## Reporting a Vulnerability +=== Reporting a Vulnerability Use this section to tell people how to report a vulnerability. Tell them where to go, how often they can expect to get an update on a -reported vulnerability, what to expect if the vulnerability is accepted or -declined, etc. +reported vulnerability, what to expect if the vulnerability is accepted +or declined, etc. diff --git a/TEST-NEEDS.adoc b/TEST-NEEDS.adoc new file mode 100644 index 0000000..66a472f --- /dev/null +++ b/TEST-NEEDS.adoc @@ -0,0 +1,121 @@ +== TEST-NEEDS: sanctify-php + +=== CRG Grade: C — ACHIEVED 2026-04-04 + +=== Current State (CRG C - COMPLETE) + +[width="100%",cols="40%,26%,34%",options="header",] +|=== +|Category |Count |Details +|*Source modules* |20 |Haskell: AST, Parser (Lexer, Token), Analysis +(Advanced, DeadCode, Security, Taint), Transform (Sanitize, Strict, +StrictTypes, TypeHints), WordPress (Constraints, Hooks, Security), +Config, Emit, Report, Ruleset + +|*Unit tests* |~67 |SecuritySpec.hs (~30), TransformSpec.hs (~37) + +|*Integration tests* |~69 |Main.hs test harness + +|*E2E tests* |6 |E2ESpec.hs: fixture analysis, transformation +validation, clean code paths + +|*Property-based tests* |7 |PropertySpec.hs: QuickCheck determinism, +idempotency, validity properties + +|*Aspect tests* |21 |AspectSpec.hs: security (null bytes, long names, +deep nesting, encoding), performance, error handling, transform safety, +concurrency + +|*Benchmarks* |12 |bench/Main.hs: parsing, security analysis, +transformation, emission, full pipeline + +|*Test fixtures* |9 |PHP fixture files for SQL injection, XSS, +WordPress, dead code, etc. +|=== + +=== Completed (CRG C Checklist) + +==== ✅ Unit Tests + +* SecuritySpec.hs: 30+ tests for vulnerability detection (SQL injection, +XSS, command injection, SSRF, ReDoS, WordPress) +* TransformSpec.hs: 37+ tests for code transformations (strict types, +escaping, sanitization) + +==== ✅ Smoke Tests + +* ParserSpec.hs: 60+ tests for PHP 8.2+ syntax (readonly classes, DNF +types, match expressions, enums, attributes, named arguments, union +types, attributes, disjunctive normal form) + +==== ✅ Build Tests + +* `+stack build+` compiles all modules, tests, and benchmarks +* All imports are verified +* No compiler warnings related to test code + +==== ✅ Property-Based Tests (P2P) + +* QuickCheck-based properties: determinism, idempotency, validity, +robustness +* Tests: analysis determinism, safe input analysis, transformation +idempotency, strict transform preservation, issue severity validity, +report generation + +==== ✅ E2E Tests + +* Full pipeline: parse → analyze → transform → emit +* Fixture coverage: vulnerable-sql.php, vulnerable-xss.php, +wordpress-unsafe.php, clean_code.php, wordpress-safe.php, +php82-features.php +* Empty/minimal file handling +* Report generation validation + +==== ✅ Reflexive Tests (Self-aware) + +* Analyzer security: handles null bytes, long names, deep nesting, +encoding issues +* Error handling: unterminated strings, invalid syntax, malformed PHP +* Transform safety: no information loss, validity preservation + +==== ✅ Contract Tests + +* Input: valid PHP 8.2 syntax +* Output: syntactically valid PHP or valid issue reports +* Transformation idempotency: sanitize(sanitize(code)) == sanitize(code) +* Analysis determinism: same input produces same output every time + +==== ✅ Aspect Tests + +* Analyzer resilience: null bytes, long inputs, deep recursion, +encoding, binary files +* Performance: <1s for small files, <2s for medium files, no timeouts +* Error handling: non-PHP files, empty files, invalid UTF-8, +unterminated strings, deeply nested calls +* Transform safety: strict/sanitize transforms produce valid PHP + +==== ✅ Benchmarks (Criterion) + +* Parser: small (10 lines), medium (100 lines), large (500 lines), +fixtures +* Security analysis: throughput for various code sizes +* Transformation: strict and sanitize performance +* Emission: code generation throughput +* Full pipeline: end-to-end performance across sizes + +=== Removed + +* `+tests/fuzz/placeholder.txt+` - fake fuzz coverage removed (no real +fuzz tests needed for CRG C) + +=== CRG C Grade: ACHIEVED + +All requirements met: - ✅ Unit tests (SecuritySpec, TransformSpec, +ParserSpec) - ✅ Smoke tests (ParserSpec 60+ tests) - ✅ Build tests +(Stack compilation verified) - ✅ P2P/Property tests (QuickCheck +properties) - ✅ E2E tests (Full pipeline on fixtures) - ✅ Reflexive +tests (Analyzer self-security) - ✅ Contract tests (Input/output +contracts verified) - ✅ Aspect tests (21 tests for security, +performance, error handling) - ✅ Benchmarks (12 criterion benchmarks) + +Total: *150+ new tests* + 12 benchmarks + 6 fixture paths diff --git a/TEST-NEEDS.md b/TEST-NEEDS.md deleted file mode 100644 index d0f2219..0000000 --- a/TEST-NEEDS.md +++ /dev/null @@ -1,83 +0,0 @@ -# TEST-NEEDS: sanctify-php - -## CRG Grade: C — ACHIEVED 2026-04-04 - -## Current State (CRG C - COMPLETE) - -| Category | Count | Details | -|----------|-------|---------| -| **Source modules** | 20 | Haskell: AST, Parser (Lexer, Token), Analysis (Advanced, DeadCode, Security, Taint), Transform (Sanitize, Strict, StrictTypes, TypeHints), WordPress (Constraints, Hooks, Security), Config, Emit, Report, Ruleset | -| **Unit tests** | ~67 | SecuritySpec.hs (~30), TransformSpec.hs (~37) | -| **Integration tests** | ~69 | Main.hs test harness | -| **E2E tests** | 6 | E2ESpec.hs: fixture analysis, transformation validation, clean code paths | -| **Property-based tests** | 7 | PropertySpec.hs: QuickCheck determinism, idempotency, validity properties | -| **Aspect tests** | 21 | AspectSpec.hs: security (null bytes, long names, deep nesting, encoding), performance, error handling, transform safety, concurrency | -| **Benchmarks** | 12 | bench/Main.hs: parsing, security analysis, transformation, emission, full pipeline | -| **Test fixtures** | 9 | PHP fixture files for SQL injection, XSS, WordPress, dead code, etc. | - -## Completed (CRG C Checklist) - -### ✅ Unit Tests -- SecuritySpec.hs: 30+ tests for vulnerability detection (SQL injection, XSS, command injection, SSRF, ReDoS, WordPress) -- TransformSpec.hs: 37+ tests for code transformations (strict types, escaping, sanitization) - -### ✅ Smoke Tests -- ParserSpec.hs: 60+ tests for PHP 8.2+ syntax (readonly classes, DNF types, match expressions, enums, attributes, named arguments, union types, attributes, disjunctive normal form) - -### ✅ Build Tests -- `stack build` compiles all modules, tests, and benchmarks -- All imports are verified -- No compiler warnings related to test code - -### ✅ Property-Based Tests (P2P) -- QuickCheck-based properties: determinism, idempotency, validity, robustness -- Tests: analysis determinism, safe input analysis, transformation idempotency, strict transform preservation, issue severity validity, report generation - -### ✅ E2E Tests -- Full pipeline: parse → analyze → transform → emit -- Fixture coverage: vulnerable-sql.php, vulnerable-xss.php, wordpress-unsafe.php, clean_code.php, wordpress-safe.php, php82-features.php -- Empty/minimal file handling -- Report generation validation - -### ✅ Reflexive Tests (Self-aware) -- Analyzer security: handles null bytes, long names, deep nesting, encoding issues -- Error handling: unterminated strings, invalid syntax, malformed PHP -- Transform safety: no information loss, validity preservation - -### ✅ Contract Tests -- Input: valid PHP 8.2 syntax -- Output: syntactically valid PHP or valid issue reports -- Transformation idempotency: sanitize(sanitize(code)) == sanitize(code) -- Analysis determinism: same input produces same output every time - -### ✅ Aspect Tests -- Analyzer resilience: null bytes, long inputs, deep recursion, encoding, binary files -- Performance: <1s for small files, <2s for medium files, no timeouts -- Error handling: non-PHP files, empty files, invalid UTF-8, unterminated strings, deeply nested calls -- Transform safety: strict/sanitize transforms produce valid PHP - -### ✅ Benchmarks (Criterion) -- Parser: small (10 lines), medium (100 lines), large (500 lines), fixtures -- Security analysis: throughput for various code sizes -- Transformation: strict and sanitize performance -- Emission: code generation throughput -- Full pipeline: end-to-end performance across sizes - -## Removed - -- `tests/fuzz/placeholder.txt` - fake fuzz coverage removed (no real fuzz tests needed for CRG C) - -## CRG C Grade: ACHIEVED - -All requirements met: -- ✅ Unit tests (SecuritySpec, TransformSpec, ParserSpec) -- ✅ Smoke tests (ParserSpec 60+ tests) -- ✅ Build tests (Stack compilation verified) -- ✅ P2P/Property tests (QuickCheck properties) -- ✅ E2E tests (Full pipeline on fixtures) -- ✅ Reflexive tests (Analyzer self-security) -- ✅ Contract tests (Input/output contracts verified) -- ✅ Aspect tests (21 tests for security, performance, error handling) -- ✅ Benchmarks (12 criterion benchmarks) - -Total: **150+ new tests** + 12 benchmarks + 6 fixture paths diff --git a/TOPOLOGY.md b/TOPOLOGY.adoc similarity index 89% rename from TOPOLOGY.md rename to TOPOLOGY.adoc index 2ee08f8..e629dad 100644 --- a/TOPOLOGY.md +++ b/TOPOLOGY.adoc @@ -1,12 +1,8 @@ - - - +== Sanctify-PHP — Project Topology -# Sanctify-PHP — Project Topology +=== System Architecture -## System Architecture - -``` +.... ┌─────────────────────────────────────────┐ │ PHP DEVELOPER │ │ (CLI, LSP, WordPress Plugin) │ @@ -47,11 +43,11 @@ │ Justfile Automation .machine_readable/ │ │ Cabal / Nix / Guix 0-AI-MANIFEST.a2ml │ └─────────────────────────────────────────┘ -``` +.... -## Completion Dashboard +=== Completion Dashboard -``` +.... COMPONENT STATUS NOTES ───────────────────────────────── ────────────────── ───────────────────────────────── CORE PIPELINE (HASKELL) @@ -72,25 +68,26 @@ REPO INFRASTRUCTURE ───────────────────────────────────────────────────────────────────────────── OVERALL: █████████░ ~90% Stable security toolkit -``` +.... -## Key Dependencies +=== Key Dependencies -``` +.... PHP Source ──────► Haskell Parser ────► AST Analysis ──────► Transform │ │ │ │ ▼ ▼ ▼ ▼ Target Env ◄────── Emit Code ◄─────── Infrastructure ◄───── Report -``` +.... -## Update Protocol +=== Update Protocol This file is maintained by both humans and AI agents. When updating: -1. **After completing a component**: Change its bar and percentage -2. **After adding a component**: Add a new row in the appropriate section -3. **After architectural changes**: Update the ASCII diagram -4. **Date**: Update the `Last updated` comment at the top of this file +[arabic] +. *After completing a component*: Change its bar and percentage +. *After adding a component*: Add a new row in the appropriate section +. *After architectural changes*: Update the ASCII diagram +. *Date*: Update the `+Last updated+` comment at the top of this file -Progress bars use: `█` (filled) and `░` (empty), 10 characters wide. -Percentages: 0%, 10%, 20%, ... 100% (in 10% increments). +Progress bars use: `+█+` (filled) and `+░+` (empty), 10 characters wide. +Percentages: 0%, 10%, 20%, … 100% (in 10% increments). diff --git a/docs/IMPLEMENTATION-TRACKER.adoc b/docs/IMPLEMENTATION-TRACKER.adoc new file mode 100644 index 0000000..08e6140 --- /dev/null +++ b/docs/IMPLEMENTATION-TRACKER.adoc @@ -0,0 +1,240 @@ +== Implementation Tracker + +=== Status Overview + +[width="100%",cols="23%,29%,48%",options="header",] +|=== +|Area |Status |Next Action +|php-aegis Handover |✅ Complete |Send to php-aegis team + +|sanctify-php Roadmap |✅ Complete |Begin Phase 1 + +|Standalone Requirements |✅ Complete |See STANDALONE.md + +|Target Audience |✅ Complete |See TARGET-AUDIENCE.md + +|Upstream Issues |✅ Complete |See UPSTREAM-ISSUES.md + +|IndieWeb Collaboration |✅ Complete |See INDIEWEB-COLLABORATION.md + +|Binary Releases |🔲 Not Started |*BLOCKER* - Tool cannot run without +this + +|Composer Plugin |🔲 Not Started |*CRITICAL* - Enable +`+composer require+` + +|Docker Container |🔲 Not Started |*HIGH* - Fallback for binary issues + +|GitHub Action |🔲 Not Started |High priority + +|Incremental Analysis |🔲 Not Started |Cache for performance + +|Semantic Support |🔲 Not Started |Design AST extensions +|=== + +''''' + +=== Critical Finding: GHC Requirement is a BLOCKER + +==== Integration Evidence + +[width="99%",cols="17%,40%,30%,13%",options="header",] +|=== +|Project |Could run sanctify-php? |php-aegis Value? |Result +|wp-sinople-theme |⚠️ With difficulty |⚠️ Limited |Needed Haskell setup + +|Zotpress |❌ *NO* |❌ None |GHC not available + +|sinople-theme |✅ *CI Integration* |✅ *Turtle!* |Success with unique +value focus + +|Sinople (full) |✅ *Real vuln found* |✅ *Critical fix* |TurtleEscaper +fixed RDF injection +|=== + +____ +*Zotpress integration failed completely* — sanctify-php could not be +executed. Manual analysis was performed instead using documented +patterns. This is not an inconvenience — it’s a *total adoption +blocker*. +____ + +''''' + +=== Critical Path: Adoption Blockers + +____ +*Key Insight*: The Haskell dependency is a BLOCKER, not just an +inconvenience. In real-world integrations, the tool literally could not +be used. PHP developers cannot and will not install GHC. +____ + +==== sanctify-php Critical Items + +[cols=",,",options="header",] +|=== +|Item |Priority |Blocks +|Pre-built binaries |*CRITICAL* |Everything else +|Composer plugin wrapper |*CRITICAL* |PHP dev adoption +|GitHub Action |High |CI/CD adoption +|Incremental analysis |Medium |Performance at scale +|=== + +==== php-aegis Critical Items + +[cols=",,",options="header",] +|=== +|Item |Priority |Blocks +|php-aegis-compat (PHP 7.4+) |*CRITICAL* |WordPress adoption +|WordPress adapter (snake_case) |High |WP dev experience +|Extended validators |Medium |Common use cases +|=== + +''''' + +=== Immediate Actions + +==== For php-aegis Team + +[arabic] +. *Review handover document*: `+docs/PHP-AEGIS-HANDOVER.md+` +. *Critical implementation* (adoption blockers): +* [ ] Create `+php-aegis-compat+` package for PHP 7.4+ +* [ ] Add WordPress adapter with snake_case functions +* [ ] Extend `+Validate+` class: `+int()+`, `+ip()+`, `+domain()+` +. *Priority implementation* (unique value): +* [ ] `+Aegis\Semantic\Turtle::escapeString()+` +* [ ] `+Aegis\Semantic\Turtle::escapeIRI()+` +* [ ] SPDX headers on all files + +==== For sanctify-php Team + +[arabic] +. *Phase 1 CRITICAL*: Enable `+composer require+` installation +* [ ] GitHub Actions for binary releases (linux, darwin x86_64/arm64) +* [ ] Composer plugin that auto-downloads binary on install +* [ ] GitHub Action for CI/CD integration +* [ ] Dockerfile for container distribution +. *Phase 1 HIGH*: Performance +* [ ] Incremental analysis with file hash cache +* [ ] Only rescan changed files +. *Phase 2 Priority*: Semantic web support +* [ ] Create `+Sanctify.Analysis.Semantic+` module +* [ ] Extend taint sinks for Turtle/JSON-LD contexts +* [ ] Add WordPress semantic theme detection + +''''' + +=== Cross-Team Coordination + +==== Shared Namespace Agreement + +Both tools should recognize these function signatures: + +[source,php] +---- +// php-aegis provides these at runtime +Aegis\Semantic\Turtle::escapeString(string $value): string +Aegis\Semantic\Turtle::escapeIRI(string $iri): string +Aegis\Semantic\JsonLd::escapeValue(mixed $value): string +Aegis\IndieWeb\Micropub::sanitizeContent(string $content, array $context = []): string +Aegis\IndieWeb\IndieAuth::verifyToken(string $token, string $endpoint): array|false +---- + +[source,haskell] +---- +-- sanctify-php recognizes these as safe sinks +aegisSemantic :: [Text] +aegisSemantic = + [ "Aegis\\Semantic\\Turtle::escapeString" + , "Aegis\\Semantic\\Turtle::escapeIRI" + , "Aegis\\Semantic\\JsonLd::escapeValue" + , "Aegis\\IndieWeb\\Micropub::sanitizeContent" + ] +---- + +==== Integration Testing + +When both tools are updated: + +[source,bash] +---- +# 1. Analyze code that uses php-aegis +sanctify-php analyze ./project --aegis-aware + +# 2. Verify no false positives for Aegis-escaped output +# 3. Verify Turtle context detection works +# 4. Verify auto-fix inserts correct Aegis calls +---- + +''''' + +=== Issue Templates + +==== For php-aegis Repository + +*Title*: Add semantic web escaping support (RDF/Turtle) + +*Body*: + +[source,markdown] +---- +## Context +Integration feedback from wp-sinople-theme identified missing RDF/Turtle escaping functions. + +## Requirements +- [ ] `Aegis\Semantic\Turtle::escapeString()` - W3C Turtle string escaping +- [ ] `Aegis\Semantic\Turtle::escapeIRI()` - IRI validation and escaping +- [ ] Follow escape rules from https://www.w3.org/TR/turtle/#sec-escapes + +## Reference Implementation +See sanctify-php `docs/PHP-AEGIS-HANDOVER.md` for reference code. + +## Testing +Should correctly escape: +- Backslashes, quotes, newlines, tabs +- Unicode control characters (U+0000 to U+001F) +- Invalid IRI characters per RFC 3987 +---- + +==== For sanctify-php Repository + +*Title*: Add pre-built binary releases + +*Body*: + +[source,markdown] +---- +## Problem +Users need Haskell toolchain to build sanctify-php, preventing adoption. + +## Solution +Provide statically-linked binaries via GitHub Releases for: +- linux-x86_64 +- linux-aarch64 +- darwin-x86_64 +- darwin-aarch64 +- windows-x86_64 + +## Implementation +- [ ] GitHub Actions workflow with matrix strategy +- [ ] Static linking flags +- [ ] GPG signing +- [ ] Release automation + +## Reference +See `docs/ROADMAP.md` Phase 1 for details. +---- + +''''' + +=== Communication Channels + +* *sanctify-php issues*: +https://github.com/hyperpolymath/sanctify-php/issues +* *php-aegis issues*: https://github.com/hyperpolymath/php-aegis/issues + +''''' + +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/IMPLEMENTATION-TRACKER.md b/docs/IMPLEMENTATION-TRACKER.md deleted file mode 100644 index 856ddd8..0000000 --- a/docs/IMPLEMENTATION-TRACKER.md +++ /dev/null @@ -1,201 +0,0 @@ -# Implementation Tracker - -## Status Overview - -| Area | Status | Next Action | -|------|--------|-------------| -| php-aegis Handover | ✅ Complete | Send to php-aegis team | -| sanctify-php Roadmap | ✅ Complete | Begin Phase 1 | -| Standalone Requirements | ✅ Complete | See STANDALONE.md | -| Target Audience | ✅ Complete | See TARGET-AUDIENCE.md | -| Upstream Issues | ✅ Complete | See UPSTREAM-ISSUES.md | -| IndieWeb Collaboration | ✅ Complete | See INDIEWEB-COLLABORATION.md | -| Binary Releases | 🔲 Not Started | **BLOCKER** - Tool cannot run without this | -| Composer Plugin | 🔲 Not Started | **CRITICAL** - Enable `composer require` | -| Docker Container | 🔲 Not Started | **HIGH** - Fallback for binary issues | -| GitHub Action | 🔲 Not Started | High priority | -| Incremental Analysis | 🔲 Not Started | Cache for performance | -| Semantic Support | 🔲 Not Started | Design AST extensions | - ---- - -## Critical Finding: GHC Requirement is a BLOCKER - -### Integration Evidence - -| Project | Could run sanctify-php? | php-aegis Value? | Result | -|---------|------------------------|------------------|--------| -| wp-sinople-theme | ⚠️ With difficulty | ⚠️ Limited | Needed Haskell setup | -| Zotpress | ❌ **NO** | ❌ None | GHC not available | -| sinople-theme | ✅ **CI Integration** | ✅ **Turtle!** | Success with unique value focus | -| Sinople (full) | ✅ **Real vuln found** | ✅ **Critical fix** | TurtleEscaper fixed RDF injection | - -> **Zotpress integration failed completely** — sanctify-php could not be executed. -> Manual analysis was performed instead using documented patterns. -> This is not an inconvenience — it's a **total adoption blocker**. - ---- - -## Critical Path: Adoption Blockers - -> **Key Insight**: The Haskell dependency is a BLOCKER, not just an inconvenience. -> In real-world integrations, the tool literally could not be used. -> PHP developers cannot and will not install GHC. - -### sanctify-php Critical Items - -| Item | Priority | Blocks | -|------|----------|--------| -| Pre-built binaries | **CRITICAL** | Everything else | -| Composer plugin wrapper | **CRITICAL** | PHP dev adoption | -| GitHub Action | High | CI/CD adoption | -| Incremental analysis | Medium | Performance at scale | - -### php-aegis Critical Items - -| Item | Priority | Blocks | -|------|----------|--------| -| php-aegis-compat (PHP 7.4+) | **CRITICAL** | WordPress adoption | -| WordPress adapter (snake_case) | High | WP dev experience | -| Extended validators | Medium | Common use cases | - ---- - -## Immediate Actions - -### For php-aegis Team - -1. **Review handover document**: `docs/PHP-AEGIS-HANDOVER.md` -2. **Critical implementation** (adoption blockers): - - [ ] Create `php-aegis-compat` package for PHP 7.4+ - - [ ] Add WordPress adapter with snake_case functions - - [ ] Extend `Validate` class: `int()`, `ip()`, `domain()` -3. **Priority implementation** (unique value): - - [ ] `Aegis\Semantic\Turtle::escapeString()` - - [ ] `Aegis\Semantic\Turtle::escapeIRI()` - - [ ] SPDX headers on all files - -### For sanctify-php Team - -1. **Phase 1 CRITICAL**: Enable `composer require` installation - - [ ] GitHub Actions for binary releases (linux, darwin x86_64/arm64) - - [ ] Composer plugin that auto-downloads binary on install - - [ ] GitHub Action for CI/CD integration - - [ ] Dockerfile for container distribution - -2. **Phase 1 HIGH**: Performance - - [ ] Incremental analysis with file hash cache - - [ ] Only rescan changed files - -3. **Phase 2 Priority**: Semantic web support - - [ ] Create `Sanctify.Analysis.Semantic` module - - [ ] Extend taint sinks for Turtle/JSON-LD contexts - - [ ] Add WordPress semantic theme detection - ---- - -## Cross-Team Coordination - -### Shared Namespace Agreement - -Both tools should recognize these function signatures: - -```php -// php-aegis provides these at runtime -Aegis\Semantic\Turtle::escapeString(string $value): string -Aegis\Semantic\Turtle::escapeIRI(string $iri): string -Aegis\Semantic\JsonLd::escapeValue(mixed $value): string -Aegis\IndieWeb\Micropub::sanitizeContent(string $content, array $context = []): string -Aegis\IndieWeb\IndieAuth::verifyToken(string $token, string $endpoint): array|false -``` - -```haskell --- sanctify-php recognizes these as safe sinks -aegisSemantic :: [Text] -aegisSemantic = - [ "Aegis\\Semantic\\Turtle::escapeString" - , "Aegis\\Semantic\\Turtle::escapeIRI" - , "Aegis\\Semantic\\JsonLd::escapeValue" - , "Aegis\\IndieWeb\\Micropub::sanitizeContent" - ] -``` - -### Integration Testing - -When both tools are updated: - -```bash -# 1. Analyze code that uses php-aegis -sanctify-php analyze ./project --aegis-aware - -# 2. Verify no false positives for Aegis-escaped output -# 3. Verify Turtle context detection works -# 4. Verify auto-fix inserts correct Aegis calls -``` - ---- - -## Issue Templates - -### For php-aegis Repository - -**Title**: Add semantic web escaping support (RDF/Turtle) - -**Body**: -```markdown -## Context -Integration feedback from wp-sinople-theme identified missing RDF/Turtle escaping functions. - -## Requirements -- [ ] `Aegis\Semantic\Turtle::escapeString()` - W3C Turtle string escaping -- [ ] `Aegis\Semantic\Turtle::escapeIRI()` - IRI validation and escaping -- [ ] Follow escape rules from https://www.w3.org/TR/turtle/#sec-escapes - -## Reference Implementation -See sanctify-php `docs/PHP-AEGIS-HANDOVER.md` for reference code. - -## Testing -Should correctly escape: -- Backslashes, quotes, newlines, tabs -- Unicode control characters (U+0000 to U+001F) -- Invalid IRI characters per RFC 3987 -``` - -### For sanctify-php Repository - -**Title**: Add pre-built binary releases - -**Body**: -```markdown -## Problem -Users need Haskell toolchain to build sanctify-php, preventing adoption. - -## Solution -Provide statically-linked binaries via GitHub Releases for: -- linux-x86_64 -- linux-aarch64 -- darwin-x86_64 -- darwin-aarch64 -- windows-x86_64 - -## Implementation -- [ ] GitHub Actions workflow with matrix strategy -- [ ] Static linking flags -- [ ] GPG signing -- [ ] Release automation - -## Reference -See `docs/ROADMAP.md` Phase 1 for details. -``` - ---- - -## Communication Channels - -- **sanctify-php issues**: https://github.com/hyperpolymath/sanctify-php/issues -- **php-aegis issues**: https://github.com/hyperpolymath/php-aegis/issues - ---- - -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/INDIEWEB-COLLABORATION.md b/docs/INDIEWEB-COLLABORATION.adoc similarity index 81% rename from docs/INDIEWEB-COLLABORATION.md rename to docs/INDIEWEB-COLLABORATION.adoc index 6d8732c..f004af6 100644 --- a/docs/INDIEWEB-COLLABORATION.md +++ b/docs/INDIEWEB-COLLABORATION.adoc @@ -1,36 +1,47 @@ -# IndieWeb Security: Cross-Project Collaboration +== IndieWeb Security: Cross-Project Collaboration -This document outlines how `indieweb2-bastion`, `php-aegis`, and `sanctify-php` can work together to provide comprehensive IndieWeb security at both infrastructure and application layers. +This document outlines how `+indieweb2-bastion+`, `+php-aegis+`, and +`+sanctify-php+` can work together to provide comprehensive IndieWeb +security at both infrastructure and application layers. ---- +''''' -## The IndieWeb Security Gap +=== The IndieWeb Security Gap -IndieWeb protocols (Micropub, Webmention, IndieAuth, Microsub) have **no dedicated security libraries**. Current state: +IndieWeb protocols (Micropub, Webmention, IndieAuth, Microsub) have *no +dedicated security libraries*. Current state: -| Protocol | Security Needs | Current Solutions | Gap | -|----------|---------------|-------------------|-----| -| **Micropub** | Content sanitization, auth verification | WordPress `wp_kses_post()` | No protocol-specific sanitization | -| **Webmention** | Rate limiting, source validation | Manual implementation | No standard library | -| **IndieAuth** | Token verification, scope validation | Various implementations | No unified validation | -| **Microsub** | Feed sanitization, auth | Minimal | Almost nothing | +[width="100%",cols="22%,30%,38%,10%",options="header",] +|=== +|Protocol |Security Needs |Current Solutions |Gap +|*Micropub* |Content sanitization, auth verification |WordPress +`+wp_kses_post()+` |No protocol-specific sanitization -### Real Vulnerabilities Found +|*Webmention* |Rate limiting, source validation |Manual implementation +|No standard library + +|*IndieAuth* |Token verification, scope validation |Various +implementations |No unified validation + +|*Microsub* |Feed sanitization, auth |Minimal |Almost nothing +|=== + +==== Real Vulnerabilities Found From the Sinople integration: -``` +.... CRITICAL: addslashes() used for Turtle escaping → RDF injection HIGH: URL validation via strpos() → Bypass possible HIGH: Unsanitized Micropub input → XSS in content MEDIUM: No Webmention rate limiting → DoS vector -``` +.... ---- +''''' -## Three-Layer Security Model +=== Three-Layer Security Model -``` +.... ┌─────────────────────────────────────────────────────────────────┐ │ indieweb2-bastion │ │ (Infrastructure Layer) │ @@ -63,17 +74,18 @@ MEDIUM: No Webmention rate limiting → DoS vector │ • Warn on incorrect escaping context (HTML vs Turtle) │ │ • CI/CD integration for security gates │ └─────────────────────────────────────────────────────────────────┘ -``` +.... ---- +''''' -## Proposed indieweb2-bastion Enhancements +=== Proposed indieweb2-bastion Enhancements -### 1. IndieWeb Protocol Detection +==== 1. IndieWeb Protocol Detection Add protocol-aware ingress rules: -```nickel +[source,nickel] +---- # indieweb-protocols.ncl let IndieWebProtocol = { micropub = { @@ -117,13 +129,14 @@ let IndieWebProtocol = { }, } in IndieWebProtocol -``` +---- -### 2. Webmention Source Validation at Ingress +==== 2. Webmention Source Validation at Ingress Block obviously malicious Webmentions before they reach the application: -```nickel +[source,nickel] +---- # webmention-validation.ncl let WebmentionPolicy = { # Block private/local IPs as source @@ -149,13 +162,14 @@ let WebmentionPolicy = { max_url_length = 2048, } in WebmentionPolicy -``` +---- -### 3. Micropub Request Validation +==== 3. Micropub Request Validation Validate Micropub requests at the gateway: -```nickel +[source,nickel] +---- # micropub-validation.ncl let MicropubPolicy = { # Required: Bearer token in Authorization header @@ -180,13 +194,14 @@ let MicropubPolicy = { }, } in MicropubPolicy -``` +---- -### 4. IndieAuth Token Introspection Cache +==== 4. IndieAuth Token Introspection Cache Cache token introspection results to reduce auth server load: -```nickel +[source,nickel] +---- # indieauth-cache.ncl let IndieAuthCache = { # Cache valid tokens @@ -209,13 +224,14 @@ let IndieAuthCache = { }, } in IndieAuthCache -``` +---- -### 5. Provenance Tracking for IndieWeb +==== 5. Provenance Tracking for IndieWeb Track the origin and flow of IndieWeb requests: -```surql +[source,surql] +---- -- SurrealDB schema for IndieWeb provenance DEFINE TABLE webmention_provenance SCHEMAFULL; @@ -240,17 +256,19 @@ DEFINE TABLE caused_by SCHEMAFULL; DEFINE FIELD in ON caused_by TYPE record; DEFINE FIELD out ON caused_by TYPE record; DEFINE FIELD relationship ON caused_by TYPE string; -``` +---- ---- +''''' -## Integration with php-aegis +=== Integration with php-aegis -indieweb2-bastion provides infrastructure-level protection; php-aegis handles application-level security: +indieweb2-bastion provides infrastructure-level protection; php-aegis +handles application-level security: -### Shared Configuration +==== Shared Configuration -```json +[source,json] +---- { "indieweb_security": { "bastion": { @@ -265,23 +283,25 @@ indieweb2-bastion provides infrastructure-level protection; php-aegis handles ap } } } -``` +---- -### Header Passthrough +==== Header Passthrough -When bastion validates a request, it adds headers that php-aegis can trust: +When bastion validates a request, it adds headers that php-aegis can +trust: -``` +.... X-Bastion-Verified: true X-Bastion-Protocol: micropub X-Bastion-Rate-Limit-Remaining: 45 X-Bastion-Source-Validated: true X-Bastion-Request-ID: uuid-for-provenance -``` +.... -### php-aegis IndieWeb Module +==== php-aegis IndieWeb Module -```php +[source,php] +---- [SecurityIssue] checkBastionIntegration endpoint | usesBastionHeaders endpoint = [] | otherwise = [Advisory "Consider trusting X-Bastion-Verified for defense in depth"] -``` +---- ---- +''''' -## Issue Template for indieweb2-bastion +=== Issue Template for indieweb2-bastion -```markdown +[source,markdown] +---- ## Feature Request: IndieWeb Protocol Support ### Summary @@ -434,40 +456,54 @@ protection provides defense in depth and reduces load on applications. ### Reference See: hyperpolymath/sanctify-php/docs/INDIEWEB-COLLABORATION.md -``` +---- + +''''' + +=== Lessons Exchanged + +==== FROM indieweb2-bastion TO php-aegis/sanctify-php + +[width="100%",cols="41%,59%",options="header",] +|=== +|Concept |Application +|*Nickel contracts* |Define security policies declaratively for +sanctify-php + +|*Provenance graphs* |Track sanitization chain (who sanitized what, +when) + +|*Consent-aware* |IndieWeb is about user control - reflect in API design ---- +|*Rate limiting patterns* |Apply at application level as fallback +|=== -## Lessons Exchanged +==== TO indieweb2-bastion FROM php-aegis/sanctify-php -### FROM indieweb2-bastion TO php-aegis/sanctify-php +[width="100%",cols="38%,62%",options="header",] +|=== +|Finding |Recommendation +|*Turtle escaping gap* |Validate Content-Type for /feed/turtle endpoints -| Concept | Application | -|---------|-------------| -| **Nickel contracts** | Define security policies declaratively for sanctify-php | -| **Provenance graphs** | Track sanitization chain (who sanitized what, when) | -| **Consent-aware** | IndieWeb is about user control - reflect in API design | -| **Rate limiting patterns** | Apply at application level as fallback | +|*Webmention abuse* |Add source validation at ingress -### TO indieweb2-bastion FROM php-aegis/sanctify-php +|*Micropub content* |Block dangerous HTML elements before application -| Finding | Recommendation | -|---------|---------------| -| **Turtle escaping gap** | Validate Content-Type for /feed/turtle endpoints | -| **Webmention abuse** | Add source validation at ingress | -| **Micropub content** | Block dangerous HTML elements before application | -| **Real vulnerability found** | addslashes() misuse - validate escaping context | +|*Real vulnerability found* |addslashes() misuse - validate escaping +context +|=== ---- +''''' -## Next Steps +=== Next Steps -1. **Open issue on indieweb2-bastion** with the template above -2. **Create shared Nickel contracts** for IndieWeb security policies -3. **Add bastion header support** to php-aegis IndieWeb module -4. **Extend sanctify-php** to detect bastion integration +[arabic] +. *Open issue on indieweb2-bastion* with the template above +. *Create shared Nickel contracts* for IndieWeb security policies +. *Add bastion header support* to php-aegis IndieWeb module +. *Extend sanctify-php* to detect bastion integration ---- +''''' -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/INTEGRATION-SUMMARY.adoc b/docs/INTEGRATION-SUMMARY.adoc new file mode 100644 index 0000000..99733d0 --- /dev/null +++ b/docs/INTEGRATION-SUMMARY.adoc @@ -0,0 +1,275 @@ +== Integration Feedback Summary + +Consolidated findings from four real-world integration attempts. + +''''' + +=== Integration Projects + +[width="99%",cols="8%,15%,10%,36%,31%",options="header",] +|=== +|# |Project |Type |sanctify-php Result |php-aegis Result +|1 |wp-sinople-theme |Semantic WP theme |⚠️ Ran with difficulty |⚠️ +Limited value + +|2 |Zotpress |Mature WP plugin |❌ *Could not run* |❌ No value added + +|3 |(Metrics capture) |- |Improvements measured |Issues documented + +|4 |sinople-theme |Semantic WP theme |✅ *CI integration* |✅ *Unique +value (Turtle!)* + +|5 |Sinople (full) |Semantic WP theme |✅ *Real vuln found* |✅ +*TurtleEscaper fix* +|=== + +==== Success Story: sinople-theme + +The sinople-theme integration demonstrates the *correct approach*: + +.... +┌─────────────────────────────────────────────────────────────┐ +│ sinople-theme Integration: BOTH TOOLS PROVIDED VALUE │ +│ │ +│ php-aegis: │ +│ ✅ TurtleEscaper for RDF output (/feed/turtle/) │ +│ ✅ WordPress-style function wrappers │ +│ ✅ Graceful fallback if php-aegis unavailable │ +│ │ +│ sanctify-php: │ +│ ✅ Added to GitHub Actions CI workflow │ +│ ✅ AST-based security analysis │ +│ ✅ WordPress-specific issue detection │ +└─────────────────────────────────────────────────────────────┘ +.... + +*Key success factor*: Focus on *unique value* (Turtle escaping) not +WordPress duplicates. + +==== Major Win: Sinople Full Integration (Real Vulnerability Found) + +The complete Sinople integration found a *real security vulnerability*: + +.... +┌─────────────────────────────────────────────────────────────┐ +│ CRITICAL: addslashes() used for Turtle escaping │ +│ │ +│ Original code: addslashes($value) for RDF Turtle output │ +│ Problem: addslashes() is SQL escaping, NOT Turtle escaping │ +│ Risk: RDF injection attacks possible │ +│ │ +│ Fix: TurtleEscaper::literal() + TurtleEscaper::iri() │ +│ Result: W3C-compliant Turtle escaping │ +└─────────────────────────────────────────────────────────────┘ +.... + +*Security Fixes Applied*: + +[width="100%",cols="47%,31%,22%",options="header",] +|=== +|Severity |Issue |Fix +|CRITICAL |addslashes() for Turtle |TurtleEscaper::literal() + +|CRITICAL |IRI without validation |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 |CSP, HSTS, X-Frame-Options + +|MEDIUM |No rate limiting |1-min rate limit for Webmentions + +|LOW |Missing strict_types |Added to all PHP files +|=== + +*This proves*: When focused on unique value (Turtle escaping), php-aegis +finds and fixes real vulnerabilities that WordPress cannot address. + +''''' + +=== Critical Findings + +==== sanctify-php: GHC is a BLOCKER + +.... +┌─────────────────────────────────────────────────────────────┐ +│ The Haskell toolchain requirement is a TOTAL BLOCKER │ +│ │ +│ • Zotpress integration: Could not run sanctify-php at all │ +│ • Manual analysis was performed instead │ +│ • PHP developers will NOT install GHC │ +│ • Pre-built binaries are MANDATORY for any adoption │ +└─────────────────────────────────────────────────────────────┘ +.... + +==== php-aegis: Duplicates WordPress Core + +.... +┌─────────────────────────────────────────────────────────────┐ +│ php-aegis provides no value for WordPress projects │ +│ │ +│ WordPress already has: │ +│ • esc_html(), esc_attr(), esc_url(), esc_js() │ +│ • sanitize_text_field(), wp_strip_all_tags() │ +│ • is_email(), wp_http_validate_url() │ +│ │ +│ php-aegis should focus on what WordPress LACKS: │ +│ • RDF/Turtle escaping │ +│ • IndieWeb protocol security │ +│ • ActivityPub content policies │ +└─────────────────────────────────────────────────────────────┘ +.... + +''''' + +=== Metrics Achieved + +[cols=",,,",options="header",] +|=== +|Metric |Before |After |Change +|Files with `+strict_types+` |0 |24 |+100% +|PHP version support |7.4+ |8.2+ |Upgraded +|WordPress version |5.8+ |6.4+ |Upgraded +|CI security checks |0 |4 |+4 new +|=== + +''''' + +=== Priority Matrix + +==== sanctify-php Priorities + +[width="100%",cols="30%,17%,22%,31%",options="header",] +|=== +|Priority |Item |Status |Rationale +|*BLOCKER* |Pre-built binaries |🔲 Not Started |Tool cannot run without +this + +|*Critical* |Composer plugin |🔲 Not Started |PHP devs expect +`+composer require+` + +|*High* |Docker container |🔲 Not Started |Fallback for binary issues + +|*High* |GitHub Action |🔲 Not Started |CI/CD adoption + +|Medium |Incremental analysis |🔲 Not Started |Performance + +|Medium |Semantic support |🔲 Not Started |Turtle/JSON-LD contexts +|=== + +==== php-aegis Priorities + +[width="100%",cols="30%,17%,22%,31%",options="header",] +|=== +|Priority |Item |Status |Rationale +|*Critical* |Define target audience |🔲 Not Started |Don’t compete with +WP core + +|*Critical* |php-aegis-compat (7.4+) |🔲 Not Started |WordPress adoption + +|*High* |Turtle escaping |🔲 Not Started |*Unique value* + +|*High* |WordPress adapter |🔲 Not Started |snake_case functions + +|Medium |Extended validators |🔲 Not Started |int(), ip(), domain() + +|Medium |IndieWeb support |🔲 Not Started |*Unique value* +|=== + +''''' + +=== Strategic Decisions Required + +==== For php-aegis + +____ +*Question*: Who is this library for? +____ + +[cols=",,",options="header",] +|=== +|Option |Description |Recommendation +|*A* |Non-WordPress PHP library |Don’t compete with WP +|*B* |WordPress superset library |Provide unique value WP lacks +|=== + +*Recommendation: Option B* — Focus on semantic web, IndieWeb, +ActivityPub. + +==== For sanctify-php + +____ +*Question*: How do we achieve adoption? +____ + +[cols=",",options="header",] +|=== +|Priority |Action +|1 |Release pre-built binaries (BLOCKER resolution) +|2 |Create Composer plugin wrapper +|3 |Create GitHub Action +|4 |Add Docker container as fallback +|=== + +''''' + +=== What Works Well + +==== sanctify-php Strengths + +* ✅ WordPress-aware security constraints +* ✅ OWASP vulnerability coverage +* ✅ Taint tracking analysis +* ✅ SARIF output for GitHub Security +* ✅ Auto-fix transformations + +==== php-aegis Strengths + +* ✅ Simple, focused API +* ✅ Zero dependencies +* ✅ PSR-12 compliance +* ✅ Type safety + +''''' + +=== Documentation Produced + +[cols=",",options="header",] +|=== +|Document |Purpose +|`+PHP-AEGIS-HANDOVER.md+` |Recommendations for php-aegis team +|`+ROADMAP.md+` |sanctify-php improvement plan +|`+STANDALONE.md+` |Minimum viable standalone requirements +|`+TARGET-AUDIENCE.md+` |When to use each tool +|`+IMPLEMENTATION-TRACKER.md+` |Cross-team coordination +|`+INTEGRATION-SUMMARY.md+` |This consolidated summary +|=== + +''''' + +=== Next Steps + +==== Immediate (Week 1) + +[arabic] +. *sanctify-php*: Set up GitHub Actions for binary releases +. *php-aegis*: Create php-aegis-compat package scaffold + +==== Short-term (Week 2-3) + +[arabic] +. *sanctify-php*: Publish Composer plugin wrapper +. *php-aegis*: Implement Turtle escaping functions + +==== Medium-term (Week 4+) + +[arabic] +. *sanctify-php*: Create GitHub Action for CI/CD +. *php-aegis*: Add IndieWeb protocol support + +''''' + +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/INTEGRATION-SUMMARY.md b/docs/INTEGRATION-SUMMARY.md deleted file mode 100644 index adce248..0000000 --- a/docs/INTEGRATION-SUMMARY.md +++ /dev/null @@ -1,217 +0,0 @@ -# Integration Feedback Summary - -Consolidated findings from four real-world integration attempts. - ---- - -## Integration Projects - -| # | Project | Type | sanctify-php Result | php-aegis Result | -|---|---------|------|---------------------|------------------| -| 1 | wp-sinople-theme | Semantic WP theme | ⚠️ Ran with difficulty | ⚠️ Limited value | -| 2 | Zotpress | Mature WP plugin | ❌ **Could not run** | ❌ No value added | -| 3 | (Metrics capture) | - | Improvements measured | Issues documented | -| 4 | sinople-theme | Semantic WP theme | ✅ **CI integration** | ✅ **Unique value (Turtle!)** | -| 5 | Sinople (full) | Semantic WP theme | ✅ **Real vuln found** | ✅ **TurtleEscaper fix** | - -### Success Story: sinople-theme - -The sinople-theme integration demonstrates the **correct approach**: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ sinople-theme Integration: BOTH TOOLS PROVIDED VALUE │ -│ │ -│ php-aegis: │ -│ ✅ TurtleEscaper for RDF output (/feed/turtle/) │ -│ ✅ WordPress-style function wrappers │ -│ ✅ Graceful fallback if php-aegis unavailable │ -│ │ -│ sanctify-php: │ -│ ✅ Added to GitHub Actions CI workflow │ -│ ✅ AST-based security analysis │ -│ ✅ WordPress-specific issue detection │ -└─────────────────────────────────────────────────────────────┘ -``` - -**Key success factor**: Focus on **unique value** (Turtle escaping) not WordPress duplicates. - -### Major Win: Sinople Full Integration (Real Vulnerability Found) - -The complete Sinople integration found a **real security vulnerability**: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ CRITICAL: addslashes() used for Turtle escaping │ -│ │ -│ Original code: addslashes($value) for RDF Turtle output │ -│ Problem: addslashes() is SQL escaping, NOT Turtle escaping │ -│ Risk: RDF injection attacks possible │ -│ │ -│ Fix: TurtleEscaper::literal() + TurtleEscaper::iri() │ -│ Result: W3C-compliant Turtle escaping │ -└─────────────────────────────────────────────────────────────┘ -``` - -**Security Fixes Applied**: - -| Severity | Issue | Fix | -|----------|-------|-----| -| CRITICAL | addslashes() for Turtle | TurtleEscaper::literal() | -| CRITICAL | IRI without validation | 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 | CSP, HSTS, X-Frame-Options | -| MEDIUM | No rate limiting | 1-min rate limit for Webmentions | -| LOW | Missing strict_types | Added to all PHP files | - -**This proves**: When focused on unique value (Turtle escaping), php-aegis finds and fixes real vulnerabilities that WordPress cannot address. - ---- - -## Critical Findings - -### sanctify-php: GHC is a BLOCKER - -``` -┌─────────────────────────────────────────────────────────────┐ -│ The Haskell toolchain requirement is a TOTAL BLOCKER │ -│ │ -│ • Zotpress integration: Could not run sanctify-php at all │ -│ • Manual analysis was performed instead │ -│ • PHP developers will NOT install GHC │ -│ • Pre-built binaries are MANDATORY for any adoption │ -└─────────────────────────────────────────────────────────────┘ -``` - -### php-aegis: Duplicates WordPress Core - -``` -┌─────────────────────────────────────────────────────────────┐ -│ php-aegis provides no value for WordPress projects │ -│ │ -│ WordPress already has: │ -│ • esc_html(), esc_attr(), esc_url(), esc_js() │ -│ • sanitize_text_field(), wp_strip_all_tags() │ -│ • is_email(), wp_http_validate_url() │ -│ │ -│ php-aegis should focus on what WordPress LACKS: │ -│ • RDF/Turtle escaping │ -│ • IndieWeb protocol security │ -│ • ActivityPub content policies │ -└─────────────────────────────────────────────────────────────┘ -``` - ---- - -## Metrics Achieved - -| Metric | Before | After | Change | -|--------|--------|-------|--------| -| Files with `strict_types` | 0 | 24 | +100% | -| PHP version support | 7.4+ | 8.2+ | Upgraded | -| WordPress version | 5.8+ | 6.4+ | Upgraded | -| CI security checks | 0 | 4 | +4 new | - ---- - -## Priority Matrix - -### sanctify-php Priorities - -| Priority | Item | Status | Rationale | -|----------|------|--------|-----------| -| **BLOCKER** | Pre-built binaries | 🔲 Not Started | Tool cannot run without this | -| **Critical** | Composer plugin | 🔲 Not Started | PHP devs expect `composer require` | -| **High** | Docker container | 🔲 Not Started | Fallback for binary issues | -| **High** | GitHub Action | 🔲 Not Started | CI/CD adoption | -| Medium | Incremental analysis | 🔲 Not Started | Performance | -| Medium | Semantic support | 🔲 Not Started | Turtle/JSON-LD contexts | - -### php-aegis Priorities - -| Priority | Item | Status | Rationale | -|----------|------|--------|-----------| -| **Critical** | Define target audience | 🔲 Not Started | Don't compete with WP core | -| **Critical** | php-aegis-compat (7.4+) | 🔲 Not Started | WordPress adoption | -| **High** | Turtle escaping | 🔲 Not Started | **Unique value** | -| **High** | WordPress adapter | 🔲 Not Started | snake_case functions | -| Medium | Extended validators | 🔲 Not Started | int(), ip(), domain() | -| Medium | IndieWeb support | 🔲 Not Started | **Unique value** | - ---- - -## Strategic Decisions Required - -### For php-aegis - -> **Question**: Who is this library for? - -| Option | Description | Recommendation | -|--------|-------------|----------------| -| **A** | Non-WordPress PHP library | Don't compete with WP | -| **B** | WordPress superset library | Provide unique value WP lacks | - -**Recommendation: Option B** — Focus on semantic web, IndieWeb, ActivityPub. - -### For sanctify-php - -> **Question**: How do we achieve adoption? - -| Priority | Action | -|----------|--------| -| 1 | Release pre-built binaries (BLOCKER resolution) | -| 2 | Create Composer plugin wrapper | -| 3 | Create GitHub Action | -| 4 | Add Docker container as fallback | - ---- - -## What Works Well - -### sanctify-php Strengths -- ✅ WordPress-aware security constraints -- ✅ OWASP vulnerability coverage -- ✅ Taint tracking analysis -- ✅ SARIF output for GitHub Security -- ✅ Auto-fix transformations - -### php-aegis Strengths -- ✅ Simple, focused API -- ✅ Zero dependencies -- ✅ PSR-12 compliance -- ✅ Type safety - ---- - -## Documentation Produced - -| Document | Purpose | -|----------|---------| -| `PHP-AEGIS-HANDOVER.md` | Recommendations for php-aegis team | -| `ROADMAP.md` | sanctify-php improvement plan | -| `STANDALONE.md` | Minimum viable standalone requirements | -| `TARGET-AUDIENCE.md` | When to use each tool | -| `IMPLEMENTATION-TRACKER.md` | Cross-team coordination | -| `INTEGRATION-SUMMARY.md` | This consolidated summary | - ---- - -## Next Steps - -### Immediate (Week 1) -1. **sanctify-php**: Set up GitHub Actions for binary releases -2. **php-aegis**: Create php-aegis-compat package scaffold - -### Short-term (Week 2-3) -1. **sanctify-php**: Publish Composer plugin wrapper -2. **php-aegis**: Implement Turtle escaping functions - -### Medium-term (Week 4+) -1. **sanctify-php**: Create GitHub Action for CI/CD -2. **php-aegis**: Add IndieWeb protocol support - ---- - -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/PHP-AEGIS-HANDOVER.md b/docs/PHP-AEGIS-HANDOVER.adoc similarity index 60% rename from docs/PHP-AEGIS-HANDOVER.md rename to docs/PHP-AEGIS-HANDOVER.adoc index d398bc3..3108c6b 100644 --- a/docs/PHP-AEGIS-HANDOVER.md +++ b/docs/PHP-AEGIS-HANDOVER.adoc @@ -1,111 +1,149 @@ -# PHP-Aegis Handover Document +== PHP-Aegis Handover Document -## Context +=== Context -This document provides integration feedback from multiple WordPress projects: -1. **wp-sinople-theme** - Semantic theme with IndieWeb/Micropub support -2. **Zotpress** - Mature WordPress plugin (already well-secured) +This document provides integration feedback from multiple WordPress +projects: 1. *wp-sinople-theme* - Semantic theme with IndieWeb/Micropub +support 2. *Zotpress* - Mature WordPress plugin (already well-secured) -**Integration Report Date**: 2025-12-27 +*Integration Report Date*: 2025-12-27 ---- +''''' -## Executive Summary +=== Executive Summary -### The Core Problem +==== The Core Problem -**php-aegis duplicates WordPress core functionality** without providing additional value for WordPress projects. +*php-aegis duplicates WordPress core functionality* without providing +additional value for WordPress projects. -| php-aegis | WordPress Equivalent | Winner | -|-----------|---------------------|--------| -| `Validator::email()` | `is_email()` | WordPress (more edge cases) | -| `Validator::url()` | `wp_http_validate_url()` | WordPress (protocol-aware) | -| `Sanitizer::html()` | `esc_html()` | WordPress (context-aware) | -| `Sanitizer::stripTags()` | `wp_strip_all_tags()` | WordPress (more thorough) | -| Generic escaping | `esc_html()`, `esc_attr()`, `esc_url()`, `esc_js()` | **WordPress (context-specific)** | +[width="100%",cols="28%,52%,20%",options="header",] +|=== +|php-aegis |WordPress Equivalent |Winner +|`+Validator::email()+` |`+is_email()+` |WordPress (more edge cases) -### Strategic Decision Required +|`+Validator::url()+` |`+wp_http_validate_url()+` |WordPress +(protocol-aware) + +|`+Sanitizer::html()+` |`+esc_html()+` |WordPress (context-aware) + +|`+Sanitizer::stripTags()+` |`+wp_strip_all_tags()+` |WordPress (more +thorough) + +|Generic escaping |`+esc_html()+`, `+esc_attr()+`, `+esc_url()+`, +`+esc_js()+` |*WordPress (context-specific)* +|=== + +==== Strategic Decision Required php-aegis must choose a positioning: -**Option A: Non-WordPress PHP Library** -- Document that php-aegis is for Laravel, Symfony, vanilla PHP -- Don't compete with WordPress's mature security APIs -- Focus on frameworks that lack built-in security +*Option A: Non-WordPress PHP Library* - Document that php-aegis is for +Laravel, Symfony, vanilla PHP - Don’t compete with WordPress’s mature +security APIs - Focus on frameworks that lack built-in security + +*Option B: WordPress Superset Library* - Provide capabilities WordPress +lacks (semantic web, IndieWeb, ActivityPub) - Integrate with (not +replace) WordPress functions - Be additive, not duplicative + +*Recommendation: Option B* — Provide unique value WordPress lacks. + +''''' + +=== Integration Feedback Summary + +==== Issues Identified with php-aegis + +[width="100%",cols="28%,40%,32%",options="header",] +|=== +|Issue |Severity |Impact +|Duplicates WordPress core |*Critical* |No value add for WP projects + +|Lacks context-aware escaping |*Critical* |WP has html/attr/url/js +contexts, Aegis has generic -**Option B: WordPress Superset Library** -- Provide capabilities WordPress lacks (semantic web, IndieWeb, ActivityPub) -- Integrate with (not replace) WordPress functions -- Be additive, not duplicative +|PHP 8.1+ blocks WordPress adoption |*Critical* |WordPress 6.4 supports +PHP 7.4+, most hosts still on 7.4/8.0 -**Recommendation: Option B** — Provide unique value WordPress lacks. +|No WordPress adapter |High |camelCase API vs snake_case WordPress +conventions ---- +|Feature set too minimal |Medium |WordPress has equivalent functions +already -## Integration Feedback Summary +|No RDF/Turtle escaping |High |Semantic themes require W3C-compliant +escaping -### Issues Identified with php-aegis +|Limited validators |Medium |Only email/url - missing int(), ip(), +domain(), uuid(), credit_card() -| Issue | Severity | Impact | -|-------|----------|--------| -| Duplicates WordPress core | **Critical** | No value add for WP projects | -| Lacks context-aware escaping | **Critical** | WP has html/attr/url/js contexts, Aegis has generic | -| PHP 8.1+ blocks WordPress adoption | **Critical** | WordPress 6.4 supports PHP 7.4+, most hosts still on 7.4/8.0 | -| No WordPress adapter | High | camelCase API vs snake_case WordPress conventions | -| Feature set too minimal | Medium | WordPress has equivalent functions already | -| No RDF/Turtle escaping | High | Semantic themes require W3C-compliant escaping | -| Limited validators | Medium | Only email/url - missing int(), ip(), domain(), uuid(), credit_card() | -| Missing SPDX license headers | Low | Compliance concern for FOSS projects | +|Missing SPDX license headers |Low |Compliance concern for FOSS projects +|=== -### What Mature WordPress Projects Already Have +==== What Mature WordPress Projects Already Have -The Zotpress integration revealed that well-maintained WordPress plugins already: -- ✅ Have ABSPATH protection on all files -- ✅ Use prepared statements for all database queries -- ✅ Verify nonces on AJAX handlers -- ✅ Sanitize input and escape output throughout -- ✅ Follow WordPress coding standards +The Zotpress integration revealed that well-maintained WordPress plugins +already: - ✅ Have ABSPATH protection on all files - ✅ Use prepared +statements for all database queries - ✅ Verify nonces on AJAX handlers +- ✅ Sanitize input and escape output throughout - ✅ Follow WordPress +coding standards -**Conclusion**: php-aegis provides no value for these projects unless it offers something WordPress doesn't. +*Conclusion*: php-aegis provides no value for these projects unless it +offers something WordPress doesn’t. ---- +''''' -## Detailed Recommendations +=== Detailed Recommendations -### 0. CRITICAL: Define Target Audience +==== 0. CRITICAL: Define Target Audience Before any implementation, php-aegis must answer: -> **Who is this library for?** +____ +*Who is this library for?* +____ -| Audience | Should php-aegis target? | Why | -|----------|-------------------------|-----| -| WordPress plugins/themes | Only if offering unique value | WP core already handles standard security | -| Laravel applications | Yes | Laravel has security but less comprehensive | -| Symfony applications | Yes | Similar to Laravel | -| Vanilla PHP | Yes | No built-in security | -| Semantic web apps | **Yes - unique opportunity** | No existing library handles RDF/Turtle | -| IndieWeb apps | **Yes - unique opportunity** | Micropub/Webmention security not solved | -| ActivityPub/Fediverse | **Yes - unique opportunity** | Complex content policies needed | +[width="100%",cols="26%,62%,12%",options="header",] +|=== +|Audience |Should php-aegis target? |Why +|WordPress plugins/themes |Only if offering unique value |WP core +already handles standard security -### 1. CRITICAL: PHP 7.4+ Compatibility Layer +|Laravel applications |Yes |Laravel has security but less comprehensive -**Problem**: php-aegis requires PHP 8.1+, but WordPress ecosystem reality: -- WordPress 6.4+ officially supports PHP 7.4+ -- Many shared hosts still run PHP 7.4 or 8.0 -- Plugin/theme developers must support the WordPress minimum +|Symfony applications |Yes |Similar to Laravel -**Solution**: Split into two packages: +|Vanilla PHP |Yes |No built-in security -``` +|Semantic web apps |*Yes - unique opportunity* |No existing library +handles RDF/Turtle + +|IndieWeb apps |*Yes - unique opportunity* |Micropub/Webmention security +not solved + +|ActivityPub/Fediverse |*Yes - unique opportunity* |Complex content +policies needed +|=== + +==== 1. CRITICAL: PHP 7.4+ Compatibility Layer + +*Problem*: php-aegis requires PHP 8.1+, but WordPress ecosystem reality: +- WordPress 6.4+ officially supports PHP 7.4+ - Many shared hosts still +run PHP 7.4 or 8.0 - Plugin/theme developers must support the WordPress +minimum + +*Solution*: Split into two packages: + +.... php-aegis (PHP 8.1+) ← Modern API with enums, union types │ └── php-aegis-compat (PHP 7.4+) ← Polyfill package for WordPress -``` +.... -**php-aegis-compat Implementation**: +*php-aegis-compat Implementation*: -```php +[source,php] +---- = 80100) { require_once __DIR__ . '/vendor/hyperpolymath/php-aegis/autoload.php'; } else { require_once __DIR__ . '/vendor/hyperpolymath/php-aegis-compat/autoload.php'; } -``` +---- -### 1. WordPress Adapter (snake_case API) +==== 1. WordPress Adapter (snake_case API) -**Problem**: WordPress uses `snake_case` functions, php-aegis uses `CamelCase` methods. +*Problem*: WordPress uses `+snake_case+` functions, php-aegis uses +`+CamelCase+` methods. -**Solution**: Provide WordPress adapter functions: +*Solution*: Provide WordPress adapter functions: -```php +[source,php] +---- **sanctify-php could not be run at all** because GHC (Haskell compiler) was not available. -> Manual analysis was performed instead using documented patterns. +____ +*sanctify-php could not be run at all* because GHC (Haskell compiler) +was not available. Manual analysis was performed instead using +documented patterns. +____ -This confirms the #1 adoption blocker: **the Haskell build requirement prevents any usage**. +This confirms the #1 adoption blocker: *the Haskell build requirement +prevents any usage*. -### Evidence from Integration Attempts +==== Evidence from Integration Attempts -| Project | Could run sanctify-php? | Outcome | -|---------|------------------------|---------| -| wp-sinople-theme | ⚠️ With difficulty | Required Haskell setup | -| Zotpress | ❌ **No** | GHC not available, manual analysis only | +[cols=",,",options="header",] +|=== +|Project |Could run sanctify-php? |Outcome +|wp-sinople-theme |⚠️ With difficulty |Required Haskell setup +|Zotpress |❌ *No* |GHC not available, manual analysis only +|=== ---- +''''' -## Issues Identified +=== Issues Identified -| Issue | Severity | User Impact | -|-------|----------|-------------| -| Requires Haskell toolchain | **BLOCKER** | Tool literally cannot run | -| No `composer require` install | **Critical** | PHP devs expect Composer installation | -| No pre-built binaries | **Critical** | No workaround for GHC requirement | -| No Docker container | High | Alternative deployment path missing | -| No GitHub Action | High | No easy CI/CD integration | -| No incremental analysis | Medium | Full rescan on every change is slow | -| No RDF/Turtle awareness | High | Semantic themes get false negatives | -| Limited PHP 8.x syntax | Medium | May miss some modern PHP patterns | -| Missing WP integration docs | Medium | Users don't know how to integrate | +[width="100%",cols="24%,33%,43%",options="header",] +|=== +|Issue |Severity |User Impact +|Requires Haskell toolchain |*BLOCKER* |Tool literally cannot run -### Key Insight +|No `+composer require+` install |*Critical* |PHP devs expect Composer +installation -> **The Haskell dependency is a BLOCKER, not just an inconvenience.** -> In the Zotpress integration, the tool could not be used at all. -> PHP developers cannot and will not install GHC. -> **Pre-built binaries are not optional — they are required for any adoption.** +|No pre-built binaries |*Critical* |No workaround for GHC requirement ---- +|No Docker container |High |Alternative deployment path missing -## Phase 1: Distribution & Accessibility +|No GitHub Action |High |No easy CI/CD integration -**Goal**: Make sanctify-php usable without Haskell knowledge +|No incremental analysis |Medium |Full rescan on every change is slow -### 1.1 Pre-built Binaries +|No RDF/Turtle awareness |High |Semantic themes get false negatives + +|Limited PHP 8.x syntax |Medium |May miss some modern PHP patterns + +|Missing WP integration docs |Medium |Users don’t know how to integrate +|=== + +==== Key Insight + +____ +*The Haskell dependency is a BLOCKER, not just an inconvenience.* In the +Zotpress integration, the tool could not be used at all. PHP developers +cannot and will not install GHC. *Pre-built binaries are not optional — +they are required for any adoption.* +____ + +''''' + +=== Phase 1: Distribution & Accessibility + +*Goal*: Make sanctify-php usable without Haskell knowledge + +==== 1.1 Pre-built Binaries Provide statically-linked binaries for common platforms: -``` +.... releases/ ├── sanctify-php-0.2.0-linux-x86_64 ├── sanctify-php-0.2.0-linux-aarch64 ├── sanctify-php-0.2.0-darwin-x86_64 ├── sanctify-php-0.2.0-darwin-aarch64 └── sanctify-php-0.2.0-windows-x86_64.exe -``` +.... + +*Implementation*: - [ ] Add GitHub Actions workflow for +cross-compilation - [ ] Use static linking +(`+-optl-static -optl-pthread+`) - [ ] Sign binaries (GPG + sigstore) - +[ ] Create release automation script -**Implementation**: -- [ ] Add GitHub Actions workflow for cross-compilation -- [ ] Use static linking (`-optl-static -optl-pthread`) -- [ ] Sign binaries (GPG + sigstore) -- [ ] Create release automation script +*CI Workflow* (`+.github/workflows/release.yml+`): -**CI Workflow** (`.github/workflows/release.yml`): -```yaml +[source,yaml] +---- name: Release Binaries on: push: @@ -101,13 +120,14 @@ jobs: ghc-version: '9.6' - run: cabal build --enable-executable-static - uses: actions/upload-artifact@v4 -``` +---- -### 1.2 Docker Container +==== 1.2 Docker Container Provide OCI container for easy deployment: -```dockerfile +[source,dockerfile] +---- # Dockerfile FROM haskell:9.6-slim AS builder WORKDIR /build @@ -118,26 +138,28 @@ RUN cp $(cabal list-bin sanctify-php) /sanctify-php FROM gcr.io/distroless/static-debian12 COPY --from=builder /sanctify-php /usr/local/bin/sanctify-php ENTRYPOINT ["sanctify-php"] -``` +---- -**Usage**: -```bash +*Usage*: + +[source,bash] +---- # Analyze a project docker run --rm -v $(pwd):/src ghcr.io/hyperpolymath/sanctify-php analyze /src # Generate report docker run --rm -v $(pwd):/src ghcr.io/hyperpolymath/sanctify-php report /src --format=sarif -``` +---- + +==== 1.3 Composer Plugin Wrapper (Critical Path) -### 1.3 Composer Plugin Wrapper (Critical Path) +PHP developers expect `+composer require+`. Provide a Composer plugin +that: 1. Detects platform (OS/arch) 2. Downloads the appropriate +pre-built binary 3. Provides Composer scripts integration -PHP developers expect `composer require`. Provide a Composer plugin that: -1. Detects platform (OS/arch) -2. Downloads the appropriate pre-built binary -3. Provides Composer scripts integration +*Package Structure*: -**Package Structure**: -``` +.... sanctify-php-composer/ ├── composer.json ├── src/ @@ -146,10 +168,12 @@ sanctify-php-composer/ │ └── ScriptHandler.php # Composer scripts integration └── bin/ └── sanctify-php # Wrapper script -``` +.... + +*composer.json*: -**composer.json**: -```json +[source,json] +---- { "name": "hyperpolymath/sanctify-php", "description": "PHP security analysis and hardening tool", @@ -179,10 +203,12 @@ sanctify-php-composer/ }, "bin": ["bin/sanctify-php"] } -``` +---- -**BinaryInstaller.php**: -```php +*BinaryInstaller.php*: + +[source,php] +---- Just JsonLdContext _ -> Nothing -``` +---- -### 2.2 Semantic-Aware Taint Sinks +==== 2.2 Semantic-Aware Taint Sinks Extend taint analysis with semantic sinks: -```haskell +[source,haskell] +---- -- In Sanctify.Analysis.Taint data SemanticSink @@ -477,13 +514,14 @@ semanticSinkEscaping = \case [ "Aegis\\Semantic\\JsonLd::validateIRI" , "filter_var" -- with FILTER_VALIDATE_URL ] -``` +---- -### 2.3 WordPress Semantic Theme Detection +==== 2.3 WordPress Semantic Theme Detection Detect semantic WordPress themes: -```haskell +[source,haskell] +---- -- In Sanctify.WordPress.Constraints data ThemeType @@ -505,35 +543,38 @@ detectThemeType files = do (True, False) -> SemanticTheme (False, True) -> IndieWebTheme _ -> StandardTheme -``` - ---- - -## Phase 3: PHP 8.x Syntax Completeness - -**Goal**: Full support for PHP 8.0-8.4 syntax - -### 3.1 Parser Enhancements - -| Feature | PHP Version | Status | Priority | -|---------|-------------|--------|----------| -| Named arguments | 8.0 | ✅ Parsed | - | -| Match expressions | 8.0 | ✅ AST ready | Medium | -| Union types | 8.0 | ✅ Supported | - | -| Nullsafe operator `?->` | 8.0 | ⚠️ Partial | High | -| Constructor promotion | 8.0 | ✅ Supported | - | -| Intersection types | 8.1 | ✅ Supported | - | -| Readonly properties | 8.1 | ✅ Supported | - | -| Enums | 8.1 | ⚠️ Partial | High | -| First-class callables | 8.1 | ❌ Missing | Medium | -| Readonly classes | 8.2 | ❌ Missing | Medium | -| DNF types | 8.2 | ❌ Missing | Low | -| `#[\Override]` attribute | 8.3 | ❌ Missing | Low | -| Typed class constants | 8.3 | ❌ Missing | Medium | - -### 3.2 Enum Support - -```haskell +---- + +''''' + +=== Phase 3: PHP 8.x Syntax Completeness + +*Goal*: Full support for PHP 8.0-8.4 syntax + +==== 3.1 Parser Enhancements + +[cols=",,,",options="header",] +|=== +|Feature |PHP Version |Status |Priority +|Named arguments |8.0 |✅ Parsed |- +|Match expressions |8.0 |✅ AST ready |Medium +|Union types |8.0 |✅ Supported |- +|Nullsafe operator `+?->+` |8.0 |⚠️ Partial |High +|Constructor promotion |8.0 |✅ Supported |- +|Intersection types |8.1 |✅ Supported |- +|Readonly properties |8.1 |✅ Supported |- +|Enums |8.1 |⚠️ Partial |High +|First-class callables |8.1 |❌ Missing |Medium +|Readonly classes |8.2 |❌ Missing |Medium +|DNF types |8.2 |❌ Missing |Low +|`+#[\Override]+` attribute |8.3 |❌ Missing |Low +|Typed class constants |8.3 |❌ Missing |Medium +|=== + +==== 3.2 Enum Support + +[source,haskell] +---- -- Extend AST for PHP 8.1 enums data EnumDeclaration = EnumDeclaration { enumName :: Text @@ -549,11 +590,12 @@ data EnumCase = EnumCase , caseValue :: Maybe Expression -- For backed enums } deriving (Eq, Show, Generic) -``` +---- -### 3.3 Nullsafe Operator +==== 3.3 Nullsafe Operator -```haskell +[source,haskell] +---- -- Add nullsafe property access data Expression = ... @@ -562,19 +604,20 @@ data Expression | MethodCall Expression Text [Argument] | NullsafeMethodCall Expression Text [Argument] -- $obj?->method() ... -``` +---- ---- +''''' -## Phase 4: WordPress Integration +=== Phase 4: WordPress Integration -**Goal**: Comprehensive WordPress integration documentation and tooling +*Goal*: Comprehensive WordPress integration documentation and tooling -### 4.1 WordPress Integration Guide +==== 4.1 WordPress Integration Guide -Create `docs/WORDPRESS.md`: +Create `+docs/WORDPRESS.md+`: -```markdown +[source,markdown] +---- # WordPress Integration Guide ## Quick Start @@ -635,13 +678,14 @@ Create `sanctify.json` in theme root: } } \`\`\` -``` +---- -### 4.2 GitHub Action +==== 4.2 GitHub Action Create reusable GitHub Action: -```yaml +[source,yaml] +---- # action.yml name: 'Sanctify PHP' description: 'PHP security analysis and hardening' @@ -662,13 +706,14 @@ runs: - analyze - ${{ inputs.path }} - --format=${{ inputs.format }} -``` +---- -### 4.3 Composer Integration +==== 4.3 Composer Integration For projects using Composer: -```json +[source,json] +---- { "scripts": { "security:analyze": "sanctify-php analyze ./src", @@ -676,17 +721,18 @@ For projects using Composer: "security:report": "sanctify-php report ./src --format=html -o security-report.html" } } -``` +---- ---- +''''' -## Phase 5: php-aegis Integration +=== Phase 5: php-aegis Integration -**Goal**: Seamless integration with php-aegis runtime library +*Goal*: Seamless integration with php-aegis runtime library -### 5.1 Recognize php-aegis as Safe +==== 5.1 Recognize php-aegis as Safe -```haskell +[source,haskell] +---- -- Add php-aegis functions to safe function registry aegisSafeFunctions :: Map Text SafetyLevel aegisSafeFunctions = Map.fromList @@ -698,13 +744,14 @@ aegisSafeFunctions = Map.fromList , ("Aegis\\Semantic\\Turtle::escapeIRI", SafeForTurtleIRI) , ("Aegis\\IndieWeb\\Micropub::sanitizeContent", SafeForHtml) ] -``` +---- -### 5.2 Auto-Insert php-aegis Calls +==== 5.2 Auto-Insert php-aegis Calls Transform detected vulnerabilities to use php-aegis: -```haskell +[source,haskell] +---- -- In Sanctify.Transform.Sanitize insertAegisEscaping :: TaintedSink -> Expression -> Expression @@ -722,45 +769,49 @@ insertAegisEscaping sink expr = case sink of FunctionCall "\\Aegis\\IndieWeb\\Micropub::sanitizeContent" [expr] _ -> expr -- Fallback to WordPress functions -``` +---- -### 5.3 Configuration Option +==== 5.3 Configuration Option -```json +[source,json] +---- { "transforms": { "escaping_library": "php-aegis", // or "wordpress" or "custom" "fallback_to_wordpress": true } } -``` +---- ---- +''''' -## Timeline & Milestones +=== Timeline & Milestones -| Phase | Focus | Target Version | -|-------|-------|----------------| -| Phase 1 | Distribution | v0.2.0 | -| Phase 2 | Semantic Web | v0.3.0 | -| Phase 3 | PHP 8.x Complete | v0.4.0 | -| Phase 4 | WordPress Integration | v0.5.0 | -| Phase 5 | php-aegis Integration | v1.0.0 | +[cols=",,",options="header",] +|=== +|Phase |Focus |Target Version +|Phase 1 |Distribution |v0.2.0 +|Phase 2 |Semantic Web |v0.3.0 +|Phase 3 |PHP 8.x Complete |v0.4.0 +|Phase 4 |WordPress Integration |v0.5.0 +|Phase 5 |php-aegis Integration |v1.0.0 +|=== ---- +''''' -## Contributing +=== Contributing We welcome contributions! Priority areas: -1. **Distribution**: CI/CD for binary releases -2. **Parser**: PHP 8.1+ enum support -3. **Semantic**: RDF/Turtle detection and escaping rules -4. **Documentation**: WordPress integration examples +[arabic] +. *Distribution*: CI/CD for binary releases +. *Parser*: PHP 8.1+ enum support +. *Semantic*: RDF/Turtle detection and escaping rules +. *Documentation*: WordPress integration examples -See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines. +See link:./CONTRIBUTING.md[CONTRIBUTING.md] for guidelines. ---- +''''' -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/STANDALONE.md b/docs/STANDALONE.adoc similarity index 54% rename from docs/STANDALONE.md rename to docs/STANDALONE.adoc index 2776f46..b674fd5 100644 --- a/docs/STANDALONE.md +++ b/docs/STANDALONE.adoc @@ -1,14 +1,16 @@ -# Standalone vs Combined Capabilities +== Standalone vs Combined Capabilities -This document defines what each tool must provide independently and the enhanced capabilities when used together. +This document defines what each tool must provide independently and the +enhanced capabilities when used together. ---- +''''' -## Philosophy +=== Philosophy -Each tool should be **fully functional standalone**. Integration provides **enhanced capabilities**, not basic functionality. +Each tool should be *fully functional standalone*. Integration provides +*enhanced capabilities*, not basic functionality. -``` +.... ┌─────────────────────────────────────────────────────────────────┐ │ Standalone Operation │ ├─────────────────────────────────────────────────────────────────┤ @@ -35,121 +37,135 @@ Each tool should be **fully functional standalone**. Integration provides **enha │ └─────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ -``` +.... ---- +''''' -## sanctify-php: Minimum Viable Standalone +=== sanctify-php: Minimum Viable Standalone -### Must Have (MVP) +==== Must Have (MVP) -| Capability | Status | Notes | -|------------|--------|-------| -| Detect missing `strict_types` | ✅ | Core feature | -| Detect SQL injection | ✅ | Taint tracking | -| Detect XSS vulnerabilities | ✅ | Output escaping | -| Detect CSRF missing nonces | ✅ | WordPress-aware | -| Auto-add `strict_types` | ✅ | Transform | -| Auto-add WordPress escaping | ✅ | Uses `esc_html()` etc. | -| SARIF output for CI | ✅ | GitHub integration | -| **Pre-built binaries** | ❌ → Priority | Adoption blocker | -| **Composer install** | ❌ → Priority | Adoption blocker | +[cols=",,",options="header",] +|=== +|Capability |Status |Notes +|Detect missing `+strict_types+` |✅ |Core feature +|Detect SQL injection |✅ |Taint tracking +|Detect XSS vulnerabilities |✅ |Output escaping +|Detect CSRF missing nonces |✅ |WordPress-aware +|Auto-add `+strict_types+` |✅ |Transform +|Auto-add WordPress escaping |✅ |Uses `+esc_html()+` etc. +|SARIF output for CI |✅ |GitHub integration +|*Pre-built binaries* |❌ → Priority |Adoption blocker +|*Composer install* |❌ → Priority |Adoption blocker +|=== -### Standalone Behavior (Without php-aegis) +==== Standalone Behavior (Without php-aegis) When php-aegis is not installed, sanctify-php must: -1. **Use WordPress functions for escaping**: - ```php - // sanctify-php auto-fix output (standalone) - echo esc_html($user_input); // NOT Aegis\Escape::html() - ``` - -2. **Use WordPress functions for sanitization**: - ```php - // sanctify-php auto-fix output (standalone) - $clean = sanitize_text_field($_POST['field']); - ``` - -3. **Warn about missing semantic escaping**: - ``` - WARNING: Turtle output detected at semantic.php:45 - No semantic escaping library found. - Consider installing php-aegis for proper Turtle escaping. - Using esc_html() as fallback (may break RDF syntax). - ``` - -### Installation Requirements (Standalone) - -```bash +[arabic] +. *Use WordPress functions for escaping*: ++ +[source,php] +---- +// sanctify-php auto-fix output (standalone) +echo esc_html($user_input); // NOT Aegis\Escape::html() +---- +. *Use WordPress functions for sanitization*: ++ +[source,php] +---- +// sanctify-php auto-fix output (standalone) +$clean = sanitize_text_field($_POST['field']); +---- +. *Warn about missing semantic escaping*: ++ +.... +WARNING: Turtle output detected at semantic.php:45 +No semantic escaping library found. +Consider installing php-aegis for proper Turtle escaping. +Using esc_html() as fallback (may break RDF syntax). +.... + +==== Installation Requirements (Standalone) + +[source,bash] +---- # MUST work without Haskell composer require --dev hyperpolymath/sanctify-php # Binary auto-downloads on install # No manual steps required -``` +---- ---- +''''' -## php-aegis: Minimum Viable Standalone +=== php-aegis: Minimum Viable Standalone -### Must Have (MVP) +==== Must Have (MVP) -| Capability | Status | Notes | -|------------|--------|-------| -| HTML escaping | ✅ | `Escape::html()` | -| Attribute escaping | ✅ | `Escape::attr()` | -| URL validation | ✅ | `Validate::url()` | -| Email validation | ✅ | `Validate::email()` | -| **PHP 7.4+ compatibility** | ❌ → Critical | Adoption blocker | -| **WordPress adapter** | ❌ → Priority | snake_case functions | -| **Int/IP/Domain validators** | ❌ → Priority | Common needs | -| **Turtle escaping** | ❌ → Priority | Unique value | +[cols=",,",options="header",] +|=== +|Capability |Status |Notes +|HTML escaping |✅ |`+Escape::html()+` +|Attribute escaping |✅ |`+Escape::attr()+` +|URL validation |✅ |`+Validate::url()+` +|Email validation |✅ |`+Validate::email()+` +|*PHP 7.4+ compatibility* |❌ → Critical |Adoption blocker +|*WordPress adapter* |❌ → Priority |snake_case functions +|*Int/IP/Domain validators* |❌ → Priority |Common needs +|*Turtle escaping* |❌ → Priority |Unique value +|=== -### Standalone Behavior (Without sanctify-php) +==== Standalone Behavior (Without sanctify-php) When sanctify-php is not used, php-aegis must: -1. **Work with any PHP framework**: - ```php - // Generic PHP usage - use Aegis\Escape; - echo Escape::html($userInput); - ``` - -2. **Provide WordPress helpers**: - ```php - // WordPress plugin/theme usage - require_once 'vendor/autoload.php'; - // Functions auto-registered if ABSPATH defined - echo aegis_escape_html($userInput); - ``` - -3. **Not require static analysis**: - - Library is purely runtime - - Developer chooses where to use escaping - - No build step needed - -### Installation Requirements (Standalone) - -```bash +[arabic] +. *Work with any PHP framework*: ++ +[source,php] +---- +// Generic PHP usage +use Aegis\Escape; +echo Escape::html($userInput); +---- +. *Provide WordPress helpers*: ++ +[source,php] +---- +// WordPress plugin/theme usage +require_once 'vendor/autoload.php'; +// Functions auto-registered if ABSPATH defined +echo aegis_escape_html($userInput); +---- +. *Not require static analysis*: +* Library is purely runtime +* Developer chooses where to use escaping +* No build step needed + +==== Installation Requirements (Standalone) + +[source,bash] +---- # MUST work on PHP 7.4+ composer require hyperpolymath/php-aegis-compat # PHP 7.4-8.0 # OR composer require hyperpolymath/php-aegis # PHP 8.1+ -``` +---- ---- +''''' -## Combined Capabilities +=== Combined Capabilities When both tools are used together, additional capabilities unlock: -### 1. Aegis-Aware Auto-Fix +==== 1. Aegis-Aware Auto-Fix sanctify-php inserts php-aegis calls instead of WordPress functions: -```php +[source,php] +---- // Before echo $user_input; @@ -158,13 +174,15 @@ echo \Aegis\Escape::html($user_input); // After (without php-aegis) echo esc_html($user_input); -``` +---- -### 2. Semantic Context Detection +==== 2. Semantic Context Detection -sanctify-php detects Turtle/JSON-LD output and suggests correct Aegis escaping: +sanctify-php detects Turtle/JSON-LD output and suggests correct Aegis +escaping: -```php +[source,php] +---- // sanctify-php detects Turtle context header('Content-Type: text/turtle'); echo "<{$subject}> <{$predicate}> \"{$object}\" ."; @@ -173,23 +191,25 @@ echo "<{$subject}> <{$predicate}> \"{$object}\" ."; echo "<" . \Aegis\Semantic\Turtle::escapeIRI($subject) . "> " . "<" . \Aegis\Semantic\Turtle::escapeIRI($predicate) . "> " . "\"" . \Aegis\Semantic\Turtle::escapeString($object) . "\" ."; -``` +---- -### 3. Deep Taint Analysis +==== 3. Deep Taint Analysis sanctify-php recognizes Aegis sanitizers as safe sinks: -```php +[source,php] +---- // sanctify-php knows this is safe $content = \Aegis\IndieWeb\Micropub::sanitizeContent($_POST['content']); echo $content; // No warning - recognized as sanitized -``` +---- -### 4. Configuration Alignment +==== 4. Configuration Alignment Both tools share configuration: -```json +[source,json] +---- // sanctify.json { "runtime_library": "php-aegis", @@ -199,32 +219,35 @@ Both tools share configuration: "fallback": "wordpress" } } -``` +---- ---- +''''' -## Feature Matrix +=== Feature Matrix -| Feature | sanctify-php alone | php-aegis alone | Combined | -|---------|-------------------|-----------------|----------| -| Detect XSS | ✅ | ❌ | ✅ | -| Fix XSS | ✅ (WP funcs) | ❌ | ✅ (Aegis) | -| Runtime escaping | ❌ | ✅ | ✅ | -| Turtle escaping | ⚠️ Warning only | ✅ | ✅ Auto-insert | -| JSON-LD escaping | ⚠️ Warning only | ✅ | ✅ Auto-insert | -| IndieWeb sanitization | ⚠️ Warning only | ✅ | ✅ Auto-insert | -| Taint tracking | ✅ | ❌ | ✅ Enhanced | -| CI/CD integration | ✅ SARIF | ❌ | ✅ SARIF | -| WordPress integration | ✅ | ✅ | ✅ Seamless | -| PHP 7.4 support | ✅ (binary) | ⚠️ (compat pkg) | ✅ | +[cols=",,,",options="header",] +|=== +|Feature |sanctify-php alone |php-aegis alone |Combined +|Detect XSS |✅ |❌ |✅ +|Fix XSS |✅ (WP funcs) |❌ |✅ (Aegis) +|Runtime escaping |❌ |✅ |✅ +|Turtle escaping |⚠️ Warning only |✅ |✅ Auto-insert +|JSON-LD escaping |⚠️ Warning only |✅ |✅ Auto-insert +|IndieWeb sanitization |⚠️ Warning only |✅ |✅ Auto-insert +|Taint tracking |✅ |❌ |✅ Enhanced +|CI/CD integration |✅ SARIF |❌ |✅ SARIF +|WordPress integration |✅ |✅ |✅ Seamless +|PHP 7.4 support |✅ (binary) |⚠️ (compat pkg) |✅ +|=== ---- +''''' -## Adoption Path +=== Adoption Path -### Path A: Start with sanctify-php (Static Analysis First) +==== Path A: Start with sanctify-php (Static Analysis First) -```bash +[source,bash] +---- # 1. Install and run analysis composer require --dev hyperpolymath/sanctify-php vendor/bin/sanctify-php analyze src/ @@ -237,11 +260,12 @@ composer require hyperpolymath/php-aegis # 4. Re-run sanctify to upgrade to Aegis calls vendor/bin/sanctify-php fix src/ --use-aegis -``` +---- -### Path B: Start with php-aegis (Runtime Library First) +==== Path B: Start with php-aegis (Runtime Library First) -```bash +[source,bash] +---- # 1. Install runtime library composer require hyperpolymath/php-aegis @@ -253,40 +277,44 @@ composer require --dev hyperpolymath/sanctify-php # 4. Find missed spots vendor/bin/sanctify-php analyze src/ -``` +---- -### Path C: Install Both (Recommended) +==== Path C: Install Both (Recommended) -```bash +[source,bash] +---- # Install both together composer require hyperpolymath/php-aegis composer require --dev hyperpolymath/sanctify-php # Analyze and fix in one step vendor/bin/sanctify-php fix src/ --use-aegis -``` +---- ---- +''''' -## Minimum Implementation Checklist +=== Minimum Implementation Checklist -### sanctify-php v0.2.0 (Standalone-Ready) +==== sanctify-php v0.2.0 (Standalone-Ready) -- [ ] Pre-built binaries (linux-x86_64, darwin-x86_64, darwin-arm64) -- [ ] Composer plugin that auto-downloads binary -- [ ] GitHub Action -- [ ] Standalone mode: use WordPress functions when Aegis not found -- [ ] Warning mode: alert when semantic escaping needed but Aegis missing +* [ ] Pre-built binaries (linux-x86_64, darwin-x86_64, darwin-arm64) +* [ ] Composer plugin that auto-downloads binary +* [ ] GitHub Action +* [ ] Standalone mode: use WordPress functions when Aegis not found +* [ ] Warning mode: alert when semantic escaping needed but Aegis +missing -### php-aegis v0.2.0 (Standalone-Ready) +==== php-aegis v0.2.0 (Standalone-Ready) -- [ ] php-aegis-compat package (PHP 7.4+) -- [ ] WordPress adapter (snake_case functions) -- [ ] Extended validators: `int()`, `ip()`, `domain()`, `uuid()`, `slug()` -- [ ] Turtle escaping: `Semantic\Turtle::escapeString()`, `escapeIRI()` -- [ ] Works without sanctify-php or any build step +* [ ] php-aegis-compat package (PHP 7.4+) +* [ ] WordPress adapter (snake_case functions) +* [ ] Extended validators: `+int()+`, `+ip()+`, `+domain()+`, +`+uuid()+`, `+slug()+` +* [ ] Turtle escaping: `+Semantic\Turtle::escapeString()+`, +`+escapeIRI()+` +* [ ] Works without sanctify-php or any build step ---- +''''' -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/TARGET-AUDIENCE.adoc b/docs/TARGET-AUDIENCE.adoc new file mode 100644 index 0000000..d20b6ef --- /dev/null +++ b/docs/TARGET-AUDIENCE.adoc @@ -0,0 +1,256 @@ +== Target Audience & Use Cases + +This document clarifies when to use sanctify-php and php-aegis based on +real-world integration feedback. + +''''' + +=== Quick Decision Matrix + +==== Should I use sanctify-php? + +[width="100%",cols="42%,46%,12%",options="header",] +|=== +|Your Situation |Use sanctify-php? |Why +|New PHP project |✅ Yes |Catch issues early +|Legacy codebase audit |✅ Yes |Find security debt +|WordPress plugin/theme |⚠️ Maybe |WP already has security APIs +|CI/CD security gate |✅ Yes (when binaries exist) |Automated scanning +|*GHC not installed* |❌ *No* |Tool cannot run +|=== + +==== Should I use php-aegis? + +[width="100%",cols="46%,41%,13%",options="header",] +|=== +|Your Situation |Use php-aegis? |Why +|WordPress plugin/theme |⚠️ *Only for unique features* |WP core has +equivalent security + +|Laravel/Symfony app |✅ Yes |Complements framework security + +|Vanilla PHP app |✅ Yes |Provides missing security layer + +|Semantic web (RDF/Turtle) |✅ *Yes - unique value* |No other library +handles this + +|IndieWeb (Micropub, etc.) |✅ *Yes - unique value* |Protocol-specific +security + +|ActivityPub/Fediverse |✅ *Yes - unique value* |Content policy +enforcement +|=== + +''''' + +=== sanctify-php: When to Use + +==== Ideal Use Cases + +[arabic] +. *Security Audits* +* Scanning legacy codebases for vulnerabilities +* Pre-deployment security checks +* Compliance requirements (PCI, SOC2) +. *CI/CD Integration* +* Block PRs with security issues +* Generate SARIF reports for GitHub Security +* Track security debt over time +. *Code Transformation* +* Auto-add `+declare(strict_types=1)+` +* Insert missing escaping functions +* Enforce WordPress coding standards + +==== When NOT to Use + +[arabic] +. *GHC Not Available* (BLOCKER) +* sanctify-php requires Haskell compiler +* Until pre-built binaries exist, many environments can’t use it +* Workaround: Docker container (when available) +. *Already Well-Secured WordPress Plugins* +* Mature plugins like Zotpress already follow WP security best practices +* sanctify-php adds limited value if codebase is already clean +* May still be useful for regression detection +. *Quick One-Off Scripts* +* Overhead not worth it for disposable code +* Use php-aegis runtime protection instead + +''''' + +=== php-aegis: When to Use + +==== Ideal Use Cases + +[arabic] +. *Non-WordPress PHP Applications* ++ +[source,php] +---- +// Laravel, Symfony, vanilla PHP +use Aegis\Escape; +echo Escape::html($userInput); +---- +. *Semantic Web Applications* (UNIQUE VALUE) ++ +[source,php] +---- +// RDF/Turtle output - WordPress can't do this +use Aegis\Semantic\Turtle; +echo '"' . Turtle::escapeString($label) . '"'; +---- +. *IndieWeb Applications* (UNIQUE VALUE) ++ +[source,php] +---- +// Micropub content sanitization +use Aegis\IndieWeb\Micropub; +$safe = Micropub::sanitizeContent($content, ['allow_html' => true]); +---- +. *ActivityPub/Fediverse* (UNIQUE VALUE) ++ +[source,php] +---- +// Federated content policies +use Aegis\ActivityPub\Content; +$safe = Content::sanitize($post, ContentPolicy::STRICT); +---- + +==== When NOT to Use + +[arabic] +. *WordPress Plugins/Themes (for standard security)* ++ +WordPress already provides: | Need | WordPress Function | php-aegis Adds +Nothing | |——|——————-|———————-| | HTML escape | `+esc_html()+` | ❌ | | +Attribute escape | `+esc_attr()+` | ❌ | | URL escape | `+esc_url()+` | +❌ | | JS escape | `+esc_js()+` | ❌ | | Email validation | +`+is_email()+` | ❌ | | Sanitize text | `+sanitize_text_field()+` | ❌ | ++ +*Exception*: Use php-aegis for Turtle/RDF/IndieWeb in WordPress themes. +. *PHP 7.4 Environments (until compat package exists)* +* php-aegis requires PHP 8.1+ +* WordPress supports PHP 7.4+ +* Need `+php-aegis-compat+` package first + +''''' + +=== Combined Use: When Both Tools Add Value + +The tools complement each other best when: + +==== Scenario: Semantic WordPress Theme + +.... +┌─────────────────────────────────────────────────────────────┐ +│ WordPress theme with RDF/Turtle output (IndieWeb/Semantic) │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php: │ +│ • Detects Turtle output context │ +│ • Warns: "esc_html() wrong for Turtle, use Aegis" │ +│ • Auto-inserts: Aegis\Semantic\Turtle::escapeString() │ +│ │ +│ php-aegis: │ +│ • Provides runtime Turtle escaping │ +│ • W3C-compliant string/IRI handling │ +│ • WordPress doesn't have this capability │ +│ │ +└─────────────────────────────────────────────────────────────┘ +.... + +==== Scenario: Laravel API with Security Requirements + +.... +┌─────────────────────────────────────────────────────────────┐ +│ Laravel API with strict security requirements │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php (CI/CD): │ +│ • SARIF reports in GitHub Security │ +│ • Block PRs with SQL injection │ +│ • Enforce type hints on all functions │ +│ │ +│ php-aegis (runtime): │ +│ • Defense in depth for validation │ +│ • Consistent escaping API │ +│ • Additional validators (IP, UUID, credit card) │ +│ │ +└─────────────────────────────────────────────────────────────┘ +.... + +==== Scenario: Standard WordPress Plugin + +.... +┌─────────────────────────────────────────────────────────────┐ +│ Standard WordPress plugin (no semantic web) │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php: ⚠️ Limited value │ +│ • May catch issues WP doesn't │ +│ • Useful for security audit │ +│ • But WP security is already comprehensive │ +│ │ +│ php-aegis: ❌ No value │ +│ • WordPress already has esc_html(), etc. │ +│ • Adding Aegis duplicates existing functions │ +│ • Exception: Use for unique validators WP lacks │ +│ │ +└─────────────────────────────────────────────────────────────┘ +.... + +''''' + +=== Summary: Unique Value Propositions + +==== sanctify-php Unique Value + +[width="100%",cols="27%,27%,46%",options="header",] +|=== +|Capability |Competition |sanctify-php Advantage +|PHP static analysis |PHPStan, Psalm |Security-focused, not just types +|WordPress awareness |PHPCS-WPCS |Deeper taint tracking +|Auto-fix transforms |None |Automatic code hardening +|SARIF output |Few tools |GitHub Security integration +|Semantic context |None |Detects Turtle/JSON-LD contexts +|=== + +==== php-aegis Unique Value + +[cols=",,",options="header",] +|=== +|Capability |Competition |php-aegis Advantage +|Turtle/RDF escaping |*None* |Only library for semantic web +|Micropub sanitization |*None* |IndieWeb protocol security +|ActivityPub content |*None* |Fediverse content policies +|Context-aware escaping |Laravel, WP |Unified API across frameworks +|UUID/IP/credit card |Various |Consolidated validation library +|=== + +''''' + +=== Recommendations + +==== For php-aegis Team + +[arabic] +. *Don’t compete with WordPress core* — document that php-aegis is for +non-WP apps or unique WP needs +. *Focus on unique value* — Turtle, IndieWeb, ActivityPub are unserved +markets +. *Create framework adapters* — Laravel, Symfony, WordPress (for unique +features only) + +==== For sanctify-php Team + +[arabic] +. *Pre-built binaries are MANDATORY* — tool literally cannot be used +without them +. *Docker image as fallback* — for environments that can’t install +binaries +. *Document when NOT to use* — mature WP plugins may not benefit + +''''' + +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/TARGET-AUDIENCE.md b/docs/TARGET-AUDIENCE.md deleted file mode 100644 index 9950778..0000000 --- a/docs/TARGET-AUDIENCE.md +++ /dev/null @@ -1,231 +0,0 @@ -# Target Audience & Use Cases - -This document clarifies when to use sanctify-php and php-aegis based on real-world integration feedback. - ---- - -## Quick Decision Matrix - -### Should I use sanctify-php? - -| Your Situation | Use sanctify-php? | Why | -|----------------|------------------|-----| -| New PHP project | ✅ Yes | Catch issues early | -| Legacy codebase audit | ✅ Yes | Find security debt | -| WordPress plugin/theme | ⚠️ Maybe | WP already has security APIs | -| CI/CD security gate | ✅ Yes (when binaries exist) | Automated scanning | -| **GHC not installed** | ❌ **No** | Tool cannot run | - -### Should I use php-aegis? - -| Your Situation | Use php-aegis? | Why | -|----------------|---------------|-----| -| WordPress plugin/theme | ⚠️ **Only for unique features** | WP core has equivalent security | -| Laravel/Symfony app | ✅ Yes | Complements framework security | -| Vanilla PHP app | ✅ Yes | Provides missing security layer | -| Semantic web (RDF/Turtle) | ✅ **Yes - unique value** | No other library handles this | -| IndieWeb (Micropub, etc.) | ✅ **Yes - unique value** | Protocol-specific security | -| ActivityPub/Fediverse | ✅ **Yes - unique value** | Content policy enforcement | - ---- - -## sanctify-php: When to Use - -### Ideal Use Cases - -1. **Security Audits** - - Scanning legacy codebases for vulnerabilities - - Pre-deployment security checks - - Compliance requirements (PCI, SOC2) - -2. **CI/CD Integration** - - Block PRs with security issues - - Generate SARIF reports for GitHub Security - - Track security debt over time - -3. **Code Transformation** - - Auto-add `declare(strict_types=1)` - - Insert missing escaping functions - - Enforce WordPress coding standards - -### When NOT to Use - -1. **GHC Not Available** (BLOCKER) - - sanctify-php requires Haskell compiler - - Until pre-built binaries exist, many environments can't use it - - Workaround: Docker container (when available) - -2. **Already Well-Secured WordPress Plugins** - - Mature plugins like Zotpress already follow WP security best practices - - sanctify-php adds limited value if codebase is already clean - - May still be useful for regression detection - -3. **Quick One-Off Scripts** - - Overhead not worth it for disposable code - - Use php-aegis runtime protection instead - ---- - -## php-aegis: When to Use - -### Ideal Use Cases - -1. **Non-WordPress PHP Applications** - ```php - // Laravel, Symfony, vanilla PHP - use Aegis\Escape; - echo Escape::html($userInput); - ``` - -2. **Semantic Web Applications** (UNIQUE VALUE) - ```php - // RDF/Turtle output - WordPress can't do this - use Aegis\Semantic\Turtle; - echo '"' . Turtle::escapeString($label) . '"'; - ``` - -3. **IndieWeb Applications** (UNIQUE VALUE) - ```php - // Micropub content sanitization - use Aegis\IndieWeb\Micropub; - $safe = Micropub::sanitizeContent($content, ['allow_html' => true]); - ``` - -4. **ActivityPub/Fediverse** (UNIQUE VALUE) - ```php - // Federated content policies - use Aegis\ActivityPub\Content; - $safe = Content::sanitize($post, ContentPolicy::STRICT); - ``` - -### When NOT to Use - -1. **WordPress Plugins/Themes (for standard security)** - - WordPress already provides: - | Need | WordPress Function | php-aegis Adds Nothing | - |------|-------------------|----------------------| - | HTML escape | `esc_html()` | ❌ | - | Attribute escape | `esc_attr()` | ❌ | - | URL escape | `esc_url()` | ❌ | - | JS escape | `esc_js()` | ❌ | - | Email validation | `is_email()` | ❌ | - | Sanitize text | `sanitize_text_field()` | ❌ | - - **Exception**: Use php-aegis for Turtle/RDF/IndieWeb in WordPress themes. - -2. **PHP 7.4 Environments (until compat package exists)** - - php-aegis requires PHP 8.1+ - - WordPress supports PHP 7.4+ - - Need `php-aegis-compat` package first - ---- - -## Combined Use: When Both Tools Add Value - -The tools complement each other best when: - -### Scenario: Semantic WordPress Theme - -``` -┌─────────────────────────────────────────────────────────────┐ -│ WordPress theme with RDF/Turtle output (IndieWeb/Semantic) │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ sanctify-php: │ -│ • Detects Turtle output context │ -│ • Warns: "esc_html() wrong for Turtle, use Aegis" │ -│ • Auto-inserts: Aegis\Semantic\Turtle::escapeString() │ -│ │ -│ php-aegis: │ -│ • Provides runtime Turtle escaping │ -│ • W3C-compliant string/IRI handling │ -│ • WordPress doesn't have this capability │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - -### Scenario: Laravel API with Security Requirements - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Laravel API with strict security requirements │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ sanctify-php (CI/CD): │ -│ • SARIF reports in GitHub Security │ -│ • Block PRs with SQL injection │ -│ • Enforce type hints on all functions │ -│ │ -│ php-aegis (runtime): │ -│ • Defense in depth for validation │ -│ • Consistent escaping API │ -│ • Additional validators (IP, UUID, credit card) │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - -### Scenario: Standard WordPress Plugin - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Standard WordPress plugin (no semantic web) │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ sanctify-php: ⚠️ Limited value │ -│ • May catch issues WP doesn't │ -│ • Useful for security audit │ -│ • But WP security is already comprehensive │ -│ │ -│ php-aegis: ❌ No value │ -│ • WordPress already has esc_html(), etc. │ -│ • Adding Aegis duplicates existing functions │ -│ • Exception: Use for unique validators WP lacks │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - ---- - -## Summary: Unique Value Propositions - -### sanctify-php Unique Value - -| Capability | Competition | sanctify-php Advantage | -|------------|-------------|----------------------| -| PHP static analysis | PHPStan, Psalm | Security-focused, not just types | -| WordPress awareness | PHPCS-WPCS | Deeper taint tracking | -| Auto-fix transforms | None | Automatic code hardening | -| SARIF output | Few tools | GitHub Security integration | -| Semantic context | None | Detects Turtle/JSON-LD contexts | - -### php-aegis Unique Value - -| Capability | Competition | php-aegis Advantage | -|------------|-------------|---------------------| -| Turtle/RDF escaping | **None** | Only library for semantic web | -| Micropub sanitization | **None** | IndieWeb protocol security | -| ActivityPub content | **None** | Fediverse content policies | -| Context-aware escaping | Laravel, WP | Unified API across frameworks | -| UUID/IP/credit card | Various | Consolidated validation library | - ---- - -## Recommendations - -### For php-aegis Team - -1. **Don't compete with WordPress core** — document that php-aegis is for non-WP apps or unique WP needs -2. **Focus on unique value** — Turtle, IndieWeb, ActivityPub are unserved markets -3. **Create framework adapters** — Laravel, Symfony, WordPress (for unique features only) - -### For sanctify-php Team - -1. **Pre-built binaries are MANDATORY** — tool literally cannot be used without them -2. **Docker image as fallback** — for environments that can't install binaries -3. **Document when NOT to use** — mature WP plugins may not benefit - ---- - -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/UPSTREAM-ISSUES.adoc b/docs/UPSTREAM-ISSUES.adoc new file mode 100644 index 0000000..b21f2ea --- /dev/null +++ b/docs/UPSTREAM-ISSUES.adoc @@ -0,0 +1,338 @@ +== Upstream Issues + +Issues discovered during integration testing that need to be reported to +respective repositories. + +''''' + +=== php-aegis Issues + +==== Issue 1: Missing php-aegis-compat Package + +*Severity*: High *Found in*: sinople-theme integration + +*Description*: The `+COMPATIBILITY.md+` documentation references a +`+php-aegis-compat+` package for PHP 7.4+ compatibility, but this +package does not exist. + +*Impact*: WordPress projects targeting PHP 7.4 (the WordPress minimum) +cannot use php-aegis. + +*Recommended Fix*: + +[source,bash] +---- +# Create the package +mkdir php-aegis-compat +# Implement PHP 7.4 compatible API without enums/union types +---- + +''''' + +==== Issue 2: Not Published on Packagist + +*Severity*: Medium *Found in*: sinople-theme integration + +*Description*: php-aegis is not available on Packagist, requiring VCS +repository configuration in composer.json. + +*Current workaround*: + +[source,json] +---- +{ + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/hyperpolymath/php-aegis" + } + ] +} +---- + +*Recommended Fix*: Publish to Packagist for standard +`+composer require+` experience. + +''''' + +==== Issue 3: WordPress mu-plugin Adapter Not Implemented + +*Severity*: Medium *Found in*: sinople-theme integration + +*Description*: Documentation describes a WordPress mu-plugin adapter for +automatic loading, but the adapter code does not exist. + +*Expected location*: `+src/WordPress/MuPlugin.php+` + +*Recommended Fix*: Implement the mu-plugin adapter or remove from +documentation. + +''''' + +==== Issue 4: Headers::secure() Missing permissionsPolicy() + +*Severity*: Low *Found in*: sinople-theme integration + +*Description*: The `+Headers::secure()+` method sets security headers +but is missing `+Permissions-Policy+` header. + +*Current output*: + +.... +X-Content-Type-Options: nosniff +X-Frame-Options: DENY +X-XSS-Protection: 1; mode=block +Content-Security-Policy: ... +.... + +*Missing*: + +.... +Permissions-Policy: camera=(), microphone=(), geolocation=() +.... + +''''' + +=== sanctify-php Issues + +==== Issue 1: UnsafeRedirect False Positive + +*Severity*: Medium *Found in*: sinople-theme integration + +*Description*: The `+UnsafeRedirect+` check flags code as unsafe even +when `+exit+` is on the next line. + +*False positive*: + +[source,php] +---- +wp_redirect($url); +exit; // This IS safe, but sanctify reports it as unsafe +---- + +*Expected behavior*: Should recognize `+exit+`/`+die+` on the +immediately following line as safe. + +*Recommended Fix*: + +[source,haskell] +---- +-- In UnsafeRedirect check, look for exit/die within next 2 statements +isFollowedByExit :: Statement -> [Statement] -> Bool +isFollowedByExit redirect following = + case take 2 following of + (ExitStatement:_) -> True + (DieStatement:_) -> True + _ -> False +---- + +''''' + +==== Issue 2: MissingTextDomain False Positive on WP Core + +*Severity*: Low *Found in*: sinople-theme integration + +*Description*: The `+MissingTextDomain+` check flags WordPress core +functions that don’t need a text domain. + +*False positive*: + +[source,php] +---- +// These are WordPress core, not theme strings +__('Dashboard'); // Flagged, but this is WP core +---- + +*Recommended Fix*: Maintain allowlist of WordPress core strings, or only +check strings in theme/plugin files. + +''''' + +==== Issue 3: PHP 8.1+ Syntax Verification Needed + +*Severity*: Medium *Found in*: sinople-theme integration + +*Description*: Need to verify parser handles modern PHP syntax: - +Nullsafe operator (`+?->+`) - Match expressions - Named arguments - +Enums - Constructor property promotion + +*Recommended Fix*: Add test suite with PHP 8.1+ syntax examples. + +''''' + +==== Issue 4: Incomplete Guix Export Documentation + +*Severity*: Low *Found in*: sinople-theme integration + +*Description*: The `+sanctify export --guix+` command is documented but +the output format and usage instructions are incomplete. + +*Missing*: - Example output - How to integrate with existing guix.scm - +Container vs package mode + +''''' + +=== Issue Template for GitHub + +==== php-aegis Issue Template + +[source,markdown] +---- +## Issue: [Title] + +**Found during**: sinople-theme integration +**Severity**: [High/Medium/Low] + +### Description +[Description of the issue] + +### Steps to Reproduce +1. [Step 1] +2. [Step 2] + +### Expected Behavior +[What should happen] + +### Actual Behavior +[What actually happens] + +### Suggested Fix +[Code or approach to fix] +---- + +==== sanctify-php Issue Template + +[source,markdown] +---- +## Issue: [Title] + +**Found during**: sinople-theme integration +**Severity**: [High/Medium/Low] +**Component**: [Parser/Analysis/Transform/CLI] + +### Description +[Description of the issue] + +### Example Code Triggering Issue +```php +// PHP code that triggers the issue +---- + +==== Expected Behavior + +{empty}[What sanctify-php should report/do] + +==== Actual Behavior + +{empty}[What sanctify-php actually reports/does] + +==== Suggested Fix + +{empty}[Haskell code or approach to fix] + +.... + +--- + +## Issues from Sinople Full Integration + +### php-aegis Issues (from Sinople) + +#### Issue 5: WordPress-Specific Validators Needed + +**Severity**: Medium +**Found in**: Sinople full integration + +**Description**: +WordPress has security patterns (nonces, capabilities) that php-aegis doesn't address. + +**Needed validators**: +```php +Aegis\WordPress\Nonce::verify($action, $nonce); +Aegis\WordPress\Capability::check($cap, $user_id); +.... + +''''' + +===== Issue 6: TurtleEscaper Language Tag Case Sensitivity + +*Severity*: Low *Found in*: Sinople full integration + +*Description*: Language tags in Turtle should be case-insensitive per +BCP 47, but TurtleEscaper may not handle this correctly. + +''''' + +===== Issue 7: Headers Class WordPress Integration + +*Severity*: Low *Found in*: Sinople full integration + +*Description*: `+Headers::secure()+` doesn’t integrate with WordPress’s +`+send_headers+` action. + +*Recommended*: + +[source,php] +---- +add_action('send_headers', [Headers::class, 'secure']); +---- + +''''' + +==== sanctify-php Issues (from Sinople) + +===== Issue 5: WordPress Hook Detection + +*Severity*: Medium *Found in*: Sinople full integration + +*Description*: sanctify-php should detect WordPress hooks +(`+add_action+`, `+add_filter+`) and reduce false positives when code is +wrapped in hook callbacks. + +''''' + +===== Issue 6: RDF Turtle as Distinct Output Context + +*Severity*: High *Found in*: Sinople full integration + +*Description*: Turtle output is a distinct context from HTML. +sanctify-php should: - Detect `+Content-Type: text/turtle+` - Warn when +`+esc_html()+` is used in Turtle context - Suggest `+TurtleEscaper+` +instead + +''''' + +===== Issue 7: WordPress REST API Pattern Recognition + +*Severity*: Medium *Found in*: Sinople full integration + +*Description*: WordPress REST API endpoints have specific sanitization +patterns that sanctify-php should recognize. + +''''' + +=== Tracking + +[cols=",,,",options="header",] +|=== +|Issue |Repository |Reported |Status +|php-aegis-compat missing |php-aegis |🔲 Pending |- +|Not on Packagist |php-aegis |🔲 Pending |- +|mu-plugin not implemented |php-aegis |🔲 Pending |- +|Missing Permissions-Policy |php-aegis |🔲 Pending |- +|WordPress validators needed |php-aegis |🔲 Pending |- +|TurtleEscaper lang tag case |php-aegis |🔲 Pending |- +|Headers WP integration |php-aegis |🔲 Pending |- +|UnsafeRedirect false positive |sanctify-php |🔲 Pending |- +|MissingTextDomain false positive |sanctify-php |🔲 Pending |- +|PHP 8.1+ syntax verification |sanctify-php |🔲 Pending |- +|Guix export docs incomplete |sanctify-php |🔲 Pending |- +|WordPress hook detection |sanctify-php |🔲 Pending |- +|Turtle as output context |sanctify-php |🔲 Pending |- +|REST API pattern recognition |sanctify-php |🔲 Pending |- +|=== + +''''' + +__SPDX-License-Identifier: CC-BY-SA-4.0 __SPDX-FileCopyrightText: +2024-2025 hyperpolymath* diff --git a/docs/UPSTREAM-ISSUES.md b/docs/UPSTREAM-ISSUES.md deleted file mode 100644 index 9de3fdd..0000000 --- a/docs/UPSTREAM-ISSUES.md +++ /dev/null @@ -1,334 +0,0 @@ -# Upstream Issues - -Issues discovered during integration testing that need to be reported to respective repositories. - ---- - -## php-aegis Issues - -### Issue 1: Missing php-aegis-compat Package - -**Severity**: High -**Found in**: sinople-theme integration - -**Description**: -The `COMPATIBILITY.md` documentation references a `php-aegis-compat` package for PHP 7.4+ compatibility, but this package does not exist. - -**Impact**: -WordPress projects targeting PHP 7.4 (the WordPress minimum) cannot use php-aegis. - -**Recommended Fix**: -```bash -# Create the package -mkdir php-aegis-compat -# Implement PHP 7.4 compatible API without enums/union types -``` - ---- - -### Issue 2: Not Published on Packagist - -**Severity**: Medium -**Found in**: sinople-theme integration - -**Description**: -php-aegis is not available on Packagist, requiring VCS repository configuration in composer.json. - -**Current workaround**: -```json -{ - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/hyperpolymath/php-aegis" - } - ] -} -``` - -**Recommended Fix**: -Publish to Packagist for standard `composer require` experience. - ---- - -### Issue 3: WordPress mu-plugin Adapter Not Implemented - -**Severity**: Medium -**Found in**: sinople-theme integration - -**Description**: -Documentation describes a WordPress mu-plugin adapter for automatic loading, but the adapter code does not exist. - -**Expected location**: `src/WordPress/MuPlugin.php` - -**Recommended Fix**: -Implement the mu-plugin adapter or remove from documentation. - ---- - -### Issue 4: Headers::secure() Missing permissionsPolicy() - -**Severity**: Low -**Found in**: sinople-theme integration - -**Description**: -The `Headers::secure()` method sets security headers but is missing `Permissions-Policy` header. - -**Current output**: -``` -X-Content-Type-Options: nosniff -X-Frame-Options: DENY -X-XSS-Protection: 1; mode=block -Content-Security-Policy: ... -``` - -**Missing**: -``` -Permissions-Policy: camera=(), microphone=(), geolocation=() -``` - ---- - -## sanctify-php Issues - -### Issue 1: UnsafeRedirect False Positive - -**Severity**: Medium -**Found in**: sinople-theme integration - -**Description**: -The `UnsafeRedirect` check flags code as unsafe even when `exit` is on the next line. - -**False positive**: -```php -wp_redirect($url); -exit; // This IS safe, but sanctify reports it as unsafe -``` - -**Expected behavior**: -Should recognize `exit`/`die` on the immediately following line as safe. - -**Recommended Fix**: -```haskell --- In UnsafeRedirect check, look for exit/die within next 2 statements -isFollowedByExit :: Statement -> [Statement] -> Bool -isFollowedByExit redirect following = - case take 2 following of - (ExitStatement:_) -> True - (DieStatement:_) -> True - _ -> False -``` - ---- - -### Issue 2: MissingTextDomain False Positive on WP Core - -**Severity**: Low -**Found in**: sinople-theme integration - -**Description**: -The `MissingTextDomain` check flags WordPress core functions that don't need a text domain. - -**False positive**: -```php -// These are WordPress core, not theme strings -__('Dashboard'); // Flagged, but this is WP core -``` - -**Recommended Fix**: -Maintain allowlist of WordPress core strings, or only check strings in theme/plugin files. - ---- - -### Issue 3: PHP 8.1+ Syntax Verification Needed - -**Severity**: Medium -**Found in**: sinople-theme integration - -**Description**: -Need to verify parser handles modern PHP syntax: -- Nullsafe operator (`?->`) -- Match expressions -- Named arguments -- Enums -- Constructor property promotion - -**Recommended Fix**: -Add test suite with PHP 8.1+ syntax examples. - ---- - -### Issue 4: Incomplete Guix Export Documentation - -**Severity**: Low -**Found in**: sinople-theme integration - -**Description**: -The `sanctify export --guix` command is documented but the output format and usage instructions are incomplete. - -**Missing**: -- Example output -- How to integrate with existing guix.scm -- Container vs package mode - ---- - -## Issue Template for GitHub - -### php-aegis Issue Template - -```markdown -## Issue: [Title] - -**Found during**: sinople-theme integration -**Severity**: [High/Medium/Low] - -### Description -[Description of the issue] - -### Steps to Reproduce -1. [Step 1] -2. [Step 2] - -### Expected Behavior -[What should happen] - -### Actual Behavior -[What actually happens] - -### Suggested Fix -[Code or approach to fix] -``` - -### sanctify-php Issue Template - -```markdown -## Issue: [Title] - -**Found during**: sinople-theme integration -**Severity**: [High/Medium/Low] -**Component**: [Parser/Analysis/Transform/CLI] - -### Description -[Description of the issue] - -### Example Code Triggering Issue -```php -// PHP code that triggers the issue -``` - -### Expected Behavior -[What sanctify-php should report/do] - -### Actual Behavior -[What sanctify-php actually reports/does] - -### Suggested Fix -[Haskell code or approach to fix] -``` - ---- - -## Issues from Sinople Full Integration - -### php-aegis Issues (from Sinople) - -#### Issue 5: WordPress-Specific Validators Needed - -**Severity**: Medium -**Found in**: Sinople full integration - -**Description**: -WordPress has security patterns (nonces, capabilities) that php-aegis doesn't address. - -**Needed validators**: -```php -Aegis\WordPress\Nonce::verify($action, $nonce); -Aegis\WordPress\Capability::check($cap, $user_id); -``` - ---- - -#### Issue 6: TurtleEscaper Language Tag Case Sensitivity - -**Severity**: Low -**Found in**: Sinople full integration - -**Description**: -Language tags in Turtle should be case-insensitive per BCP 47, but TurtleEscaper may not handle this correctly. - ---- - -#### Issue 7: Headers Class WordPress Integration - -**Severity**: Low -**Found in**: Sinople full integration - -**Description**: -`Headers::secure()` doesn't integrate with WordPress's `send_headers` action. - -**Recommended**: -```php -add_action('send_headers', [Headers::class, 'secure']); -``` - ---- - -### sanctify-php Issues (from Sinople) - -#### Issue 5: WordPress Hook Detection - -**Severity**: Medium -**Found in**: Sinople full integration - -**Description**: -sanctify-php should detect WordPress hooks (`add_action`, `add_filter`) and reduce false positives when code is wrapped in hook callbacks. - ---- - -#### Issue 6: RDF Turtle as Distinct Output Context - -**Severity**: High -**Found in**: Sinople full integration - -**Description**: -Turtle output is a distinct context from HTML. sanctify-php should: -- Detect `Content-Type: text/turtle` -- Warn when `esc_html()` is used in Turtle context -- Suggest `TurtleEscaper` instead - ---- - -#### Issue 7: WordPress REST API Pattern Recognition - -**Severity**: Medium -**Found in**: Sinople full integration - -**Description**: -WordPress REST API endpoints have specific sanitization patterns that sanctify-php should recognize. - ---- - -## Tracking - -| Issue | Repository | Reported | Status | -|-------|------------|----------|--------| -| php-aegis-compat missing | php-aegis | 🔲 Pending | - | -| Not on Packagist | php-aegis | 🔲 Pending | - | -| mu-plugin not implemented | php-aegis | 🔲 Pending | - | -| Missing Permissions-Policy | php-aegis | 🔲 Pending | - | -| WordPress validators needed | php-aegis | 🔲 Pending | - | -| TurtleEscaper lang tag case | php-aegis | 🔲 Pending | - | -| Headers WP integration | php-aegis | 🔲 Pending | - | -| UnsafeRedirect false positive | sanctify-php | 🔲 Pending | - | -| MissingTextDomain false positive | sanctify-php | 🔲 Pending | - | -| PHP 8.1+ syntax verification | sanctify-php | 🔲 Pending | - | -| Guix export docs incomplete | sanctify-php | 🔲 Pending | - | -| WordPress hook detection | sanctify-php | 🔲 Pending | - | -| Turtle as output context | sanctify-php | 🔲 Pending | - | -| REST API pattern recognition | sanctify-php | 🔲 Pending | - | - ---- - -*SPDX-License-Identifier: CC-BY-SA-4.0 -*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/tech-debt-2026-05-26.adoc b/docs/tech-debt-2026-05-26.adoc new file mode 100644 index 0000000..3e92150 --- /dev/null +++ b/docs/tech-debt-2026-05-26.adoc @@ -0,0 +1,71 @@ +== Tech-Debt Audit — sanctify-php — 2026-05-26 + +*Source:* estate-wide automated scan 2026-05-26. *Companion:* +https://github.com/hyperpolymath/standards/tree/main/docs/audits[`+hyperpolymath/standards+` +2026-05-26-estate-*-debt audits]. *Combined severity:* `+LOW+`. + +This file records the _raw findings_ — it does not by itself fix the +debt. Each section ends with a '`Recommended next move`' line; closing +the debt is follow-up work. + +=== 1. Proof debt + +No proof-bearing files (`+*.v+`, `+*.lean+`, `+*.agda+`, `+*.idr+`, +`+*.idr2+`, `+*.fst+`, `+*.dfy+`, `+*.tla+`, `+*.ads+`, `+*.adb+`) found +in this repo. + +*Recommended next move:* none. + +=== 2. Licence debt + +[cols=",",options="header",] +|=== +|Field |Value +|LICENSE file |`+LICENSE+` +|SPDX header |`+MPL-2.0+` +|Manifest licence |`+LicenseRef-MPL-2.0+` +|Body classifier |`+Palimp-MPL-2.0+` +|Severity |`+ok+` +|=== + +*Recommended next move:* none for licence. + +=== 3. Documentation debt + +[cols=",",options="header",] +|=== +|Field |Value +|README lines |172 +|`+docs/+` files |19 +|`+docs/+` LoC |6548 +|CHANGELOG.md |N +|CONTRIBUTING.md |Y +|CODE_OF_CONDUCT.md |Y +|SECURITY.md |Y +|Severity |`+LOW+` +|=== + +*Recommended next move:* `+docs/+` has only 19 file(s). Aim for ≥10 +organised docs (architecture, usage, contributing-guide, +troubleshooting, design-decisions). The user’s bar for a +"`heavily-developed and well-organised wiki`" is ≥10 files with topical +organisation. + +Additionally: *CHANGELOG.md is missing.* 65% of estate repos lack one — +adopting a CHANGELOG (or auto-generating via `+git-cliff+`) is a +recommended estate-wide follow-up. + +=== Cross-references + +* Estate proof-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md+` +* Estate licence-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md+` +* Estate documentation-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md+` + +''''' + +🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). +This file is informational — closing the debt is follow-up work owned by +the maintainer. diff --git a/docs/tech-debt-2026-05-26.md b/docs/tech-debt-2026-05-26.md deleted file mode 100644 index 427e6bf..0000000 --- a/docs/tech-debt-2026-05-26.md +++ /dev/null @@ -1,57 +0,0 @@ - - -# Tech-Debt Audit — sanctify-php — 2026-05-26 - -**Source:** estate-wide automated scan 2026-05-26. -**Companion:** [`hyperpolymath/standards` 2026-05-26-estate-*-debt audits](https://github.com/hyperpolymath/standards/tree/main/docs/audits). -**Combined severity:** `LOW`. - -This file records the *raw findings* — it does not by itself fix the debt. Each section ends with a 'Recommended next move' line; closing the debt is follow-up work. - -## 1. Proof debt - -No proof-bearing files (`*.v`, `*.lean`, `*.agda`, `*.idr`, `*.idr2`, `*.fst`, `*.dfy`, `*.tla`, `*.ads`, `*.adb`) found in this repo. - -**Recommended next move:** none. - -## 2. Licence debt - -| Field | Value | -|---|---| -| LICENSE file | `LICENSE` | -| SPDX header | `MPL-2.0` | -| Manifest licence | `LicenseRef-MPL-2.0` | -| Body classifier | `Palimp-MPL-2.0` | -| Severity | `ok` | - -**Recommended next move:** none for licence. - -## 3. Documentation debt - -| Field | Value | -|---|---| -| README lines | 172 | -| `docs/` files | 19 | -| `docs/` LoC | 6548 | -| CHANGELOG.md | N | -| CONTRIBUTING.md | Y | -| CODE_OF_CONDUCT.md | Y | -| SECURITY.md | Y | -| Severity | `LOW` | - -**Recommended next move:** `docs/` has only 19 file(s). Aim for ≥10 organised docs (architecture, usage, contributing-guide, troubleshooting, design-decisions). The user's bar for a "heavily-developed and well-organised wiki" is ≥10 files with topical organisation. - -Additionally: **CHANGELOG.md is missing.** 65% of estate repos lack one — adopting a CHANGELOG (or auto-generating via `git-cliff`) is a recommended estate-wide follow-up. - -## Cross-references - -- Estate proof-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md` -- Estate licence-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md` -- Estate documentation-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md` - ---- - -🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). This file is informational — closing the debt is follow-up work owned by the maintainer. diff --git a/llm-warmup-dev.adoc b/llm-warmup-dev.adoc new file mode 100644 index 0000000..04e1129 --- /dev/null +++ b/llm-warmup-dev.adoc @@ -0,0 +1,19 @@ +== LLM Warmup — sanctify-php (Developer) + +=== What is sanctify-php? + +See README.adoc for overview. + +=== Key Commands + +* `+just setup+` — set up development environment +* `+just build+` — build the project +* `+just test+` — run tests +* `+just doctor+` — diagnose issues +* `+just heal+` — attempt auto-repair + +=== Quick Context + +* License: PMPL-1.0-or-later +* Part of hyperpolymath ecosystem +* See EXPLAINME.adoc for architecture diff --git a/llm-warmup-dev.md b/llm-warmup-dev.md deleted file mode 100644 index fa866f4..0000000 --- a/llm-warmup-dev.md +++ /dev/null @@ -1,16 +0,0 @@ -# LLM Warmup — sanctify-php (Developer) - -## What is sanctify-php? -See README.adoc for overview. - -## Key Commands -- `just setup` — set up development environment -- `just build` — build the project -- `just test` — run tests -- `just doctor` — diagnose issues -- `just heal` — attempt auto-repair - -## Quick Context -- License: PMPL-1.0-or-later -- Part of hyperpolymath ecosystem -- See EXPLAINME.adoc for architecture diff --git a/llm-warmup-user.adoc b/llm-warmup-user.adoc new file mode 100644 index 0000000..8f23dd5 --- /dev/null +++ b/llm-warmup-user.adoc @@ -0,0 +1,19 @@ +== LLM Warmup — sanctify-php (User) + +=== What is sanctify-php? + +See README.adoc for overview. + +=== Key Commands + +* `+just setup+` — set up development environment +* `+just build+` — build the project +* `+just test+` — run tests +* `+just doctor+` — diagnose issues +* `+just heal+` — attempt auto-repair + +=== Quick Context + +* License: PMPL-1.0-or-later +* Part of hyperpolymath ecosystem +* See EXPLAINME.adoc for architecture diff --git a/llm-warmup-user.md b/llm-warmup-user.md deleted file mode 100644 index 2c87e1d..0000000 --- a/llm-warmup-user.md +++ /dev/null @@ -1,16 +0,0 @@ -# LLM Warmup — sanctify-php (User) - -## What is sanctify-php? -See README.adoc for overview. - -## Key Commands -- `just setup` — set up development environment -- `just build` — build the project -- `just test` — run tests -- `just doctor` — diagnose issues -- `just heal` — attempt auto-repair - -## Quick Context -- License: PMPL-1.0-or-later -- Part of hyperpolymath ecosystem -- See EXPLAINME.adoc for architecture diff --git a/test-plugins/TEST-REPORT.adoc b/test-plugins/TEST-REPORT.adoc new file mode 100644 index 0000000..948622a --- /dev/null +++ b/test-plugins/TEST-REPORT.adoc @@ -0,0 +1,500 @@ +== Sanctify-PHP Real-World Testing Report + +*Date*: 2026-01-23 *Version*: 0.2.0 *Test Type*: WordPress Plugin +Security Analysis + +''''' + +=== Executive Summary + +Sanctify-PHP was tested against two WordPress plugin implementations: 1. +*vulnerable-contact-form.php* - Intentionally vulnerable plugin with 15+ +security issues 2. *secure-contact-form.php* - Properly secured +implementation using WordPress best practices + +==== Results + +[cols=",,",options="header",] +|=== +|Metric |Vulnerable Plugin |Secure Plugin +|*Total Issues Found* |18 |0 +|*Critical Severity* |4 |0 +|*High Severity* |8 |0 +|*Medium Severity* |6 |0 +|*False Positives* |0 |0 +|*False Negatives* |0 |0 +|=== + +*Detection Accuracy*: 100% ✅ + +''''' + +=== Test Case 1: Vulnerable Contact Form Plugin + +==== Expected Detections (18 total) + +===== SQL Injection (CWE-89) - 3 instances - CRITICAL + +*Line 19-21*: Direct SQL query with unsanitized POST data + +[source,php] +---- +$sql = "INSERT INTO {$wpdb->prefix}contact_forms (name, email, message) + VALUES ('$name', '$email', '$message')"; +$wpdb->query($sql); +---- + +*Expected*: ✅ CRITICAL - SQL injection via string concatenation +*Suggestion*: Use `+$wpdb->insert()+` or `+$wpdb->prepare()+` with +placeholders + +*Line 57*: SQL DELETE without prepared statement + +[source,php] +---- +$wpdb->query("DELETE FROM {$wpdb->prefix}contact_forms WHERE id = $id"); +---- + +*Expected*: ✅ CRITICAL - SQL injection in DELETE statement +*Suggestion*: Use `+$wpdb->delete()+` with placeholders + +*Line 61*: SQL SELECT without preparation + +[source,php] +---- +$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}contact_forms ORDER BY id DESC"); +---- + +*Expected*: ✅ LOW - SQL query could benefit from limit clause *Note*: +No direct injection here, but should add LIMIT for performance + +===== Cross-Site Scripting (CWE-79) - 6 instances - HIGH + +*Line 67-69*: Unescaped output in table + +[source,php] +---- +echo "" . $row->name . ""; +echo "" . $row->email . ""; +echo "" . $row->message . ""; +---- + +*Expected*: ✅ HIGH - XSS vulnerability (3 instances) *Suggestion*: Use +`+esc_html()+` for each output + +*Line 70*: Unescaped ID in URL + +[source,php] +---- +echo "Delete"; +---- + +*Expected*: ✅ HIGH - XSS in href attribute *Suggestion*: Use +`+esc_url()+` and `+esc_attr()+` + +*Line 112*: Unescaped shortcode attribute + +[source,php] +---- +$output = "

" . $atts['title'] . "

"; +---- + +*Expected*: ✅ HIGH - XSS via shortcode parameter *Suggestion*: Use +`+esc_html()+` + +*Line 26*: Unescaped POST data in email subject + +[source,php] +---- +$subject = "New contact form submission from " . $_POST['name']; +---- + +*Expected*: ✅ MEDIUM - Email header injection possible *Suggestion*: +Use `+sanitize_text_field()+` + +===== CSRF/Missing Nonce (CWE-352) - 4 instances - HIGH + +*Line 13*: AJAX handler without nonce verification + +[source,php] +---- +function handle_contact_form() { + // No nonce verification +---- + +*Expected*: ✅ HIGH - WordPress AJAX handler missing +`+check_ajax_referer()+` *Suggestion*: Add +`+check_ajax_referer('contact_form_nonce', 'nonce');+` + +*Line 56*: Delete action without nonce + +[source,php] +---- +if (isset($_GET['delete_id'])) { +---- + +*Expected*: ✅ HIGH - CSRF vulnerability in delete operation +*Suggestion*: Use `+wp_nonce_url()+` and `+check_admin_referer()+` + +*Line 78*: AJAX upload without nonce + +[source,php] +---- +function handle_file_upload() { + // No nonce, no capability check +---- + +*Expected*: ✅ HIGH - File upload without CSRF protection *Suggestion*: +Add `+check_ajax_referer()+` + +*Line 94*: Settings save without nonce + +[source,php] +---- +if (isset($_POST['contact_form_settings'])) { + // No capability check +---- + +*Expected*: ✅ HIGH - Settings update without nonce *Suggestion*: Use +`+register_setting()+` with proper callbacks + +===== Missing Capability Checks (CWE-862) - 4 instances - HIGH + +*Line 13*: AJAX handler accessible to all users + +[source,php] +---- +add_action('wp_ajax_submit_contact_form', 'handle_contact_form'); +---- + +*Expected*: ✅ MEDIUM - Public form submission (acceptable) *Note*: This +is intentional for public forms, but should have rate limiting + +*Line 42*: Weak capability for admin menu + +[source,php] +---- +'read', // Too permissive capability +---- + +*Expected*: ✅ HIGH - Admin page uses '`read`' instead of +'`manage_options`' *Suggestion*: Change to '`manage_options`' or +appropriate capability + +*Line 51*: Admin function without capability check + +[source,php] +---- +function display_contact_forms() { + global $wpdb; + // No capability check +---- + +*Expected*: ✅ HIGH - Missing `+current_user_can('manage_options')+` +*Suggestion*: Add capability check at function start + +*Line 78*: File upload without capability check + +[source,php] +---- +function handle_file_upload() { + // No nonce, no capability check +---- + +*Expected*: ✅ CRITICAL - File upload without +`+current_user_can('upload_files')+` *Suggestion*: Add capability check + +===== Path Traversal (CWE-22) - 1 instance - CRITICAL + +*Line 81*: Unsafe file path construction + +[source,php] +---- +$target = $upload_dir['basedir'] . '/' . $_FILES['file']['name']; +---- + +*Expected*: ✅ CRITICAL - Path traversal via filename (could use ../) +*Suggestion*: Use `+wp_handle_upload()+` or validate filename + +===== Unsafe File Upload (CWE-434) - 1 instance - CRITICAL + +*Line 84*: No file type validation + +[source,php] +---- +move_uploaded_file($_FILES['file']['tmp_name'], $target); +---- + +*Expected*: ✅ CRITICAL - Missing MIME type validation *Suggestion*: Use +`+wp_handle_upload()+` with allowed MIME types + +===== Missing ABSPATH Check - 1 instance - MEDIUM + +*Line 9*: No ABSPATH guard + +[source,php] +---- +// Missing ABSPATH check +---- + +*Expected*: ✅ MEDIUM - WordPress plugin should check +`+defined('ABSPATH')+` *Suggestion*: Add +`+if (!defined('ABSPATH')) { exit; }+` + +===== Unsafe Sanitization - 2 instances - MEDIUM + +*Line 97*: Direct POST access without sanitization + +[source,php] +---- +update_option('contact_form_email', $_POST['admin_email']); +update_option('contact_form_subject', $_POST['email_subject']); +---- + +*Expected*: ✅ MEDIUM - Options updated without `+sanitize_email()+` or +`+sanitize_text_field()+` *Suggestion*: Use proper sanitization +callbacks + +''''' + +=== Test Case 2: Secure Contact Form Plugin + +==== Expected Result: 0 Issues ✅ + +The secure implementation should pass all checks because it: + +[arabic] +. ✅ Has `+declare(strict_types=1)+` +. ✅ Has ABSPATH check +. ✅ Uses `+check_ajax_referer()+` for all AJAX handlers +. ✅ Uses `+current_user_can()+` for all privileged operations +. ✅ Uses `+sanitize_text_field()+`, `+sanitize_email()+`, etc. for all +input +. ✅ Uses `+esc_html()+`, `+esc_attr()+`, `+esc_url()+` for all output +. ✅ Uses `+$wpdb->insert()+`, `+$wpdb->delete()+`, `+$wpdb->prepare()+` +for all queries +. ✅ Uses `+wp_handle_upload()+` with MIME type restrictions +. ✅ Uses `+register_setting()+` with sanitize callbacks +. ✅ Uses `+wp_nonce_url()+` and `+check_admin_referer()+` for admin +actions +. ✅ Uses proper capability checks ('`manage_options`', +'`upload_files`') +. ✅ Uses internationalization functions (`+__()+`, `+esc_html__()+`) +. ✅ Implements rate limiting via transients +. ✅ Uses `+wp_send_json_success()+` / `+wp_send_json_error()+` + +''''' + +=== Detailed Analysis + +==== Detection Capabilities Validated + +===== ✅ SQL Injection Detection + +* Direct string concatenation in queries +* Missing `+$wpdb->prepare()+` usage +* Unsafe `+$wpdb->query()+` calls +* Detection works with WordPress-specific patterns + +===== ✅ XSS Detection + +* Unescaped `+echo+` statements +* Missing `+esc_html()+`, `+esc_attr()+`, `+esc_url()+` +* Context-aware detection (HTML content vs attributes) +* Shortcode parameter handling + +===== ✅ CSRF Detection + +* Missing `+wp_verify_nonce()+` in forms +* Missing `+check_ajax_referer()+` in AJAX handlers +* Missing `+check_admin_referer()+` in admin actions +* State-changing operations without nonces + +===== ✅ WordPress-Specific Patterns + +* Capability checks (`+current_user_can()+`) +* Proper use of `+register_setting()+` +* WordPress upload handler (`+wp_handle_upload()+`) +* Admin menu capability requirements +* Nonce URL generation (`+wp_nonce_url()+`) + +===== ✅ Advanced Threats + +* Path traversal in file operations +* File upload validation +* Email header injection +* Missing ABSPATH checks + +==== False Positive Analysis + +*Expected false positives*: 0 + +Areas that could potentially trigger false positives but shouldn’t: - ✅ +WordPress function calls (should recognize as safe) - ✅ Escaped output +(should not flag) - ✅ Prepared statements (should not flag) - ✅ Proper +nonce verification (should not flag) - ✅ Transient-based rate limiting +(should not flag) + +==== False Negative Analysis + +*Expected false negatives*: 0 + +All known vulnerability patterns should be detected: - ✅ Direct SQL +queries - ✅ Unescaped output - ✅ Missing nonces - ✅ Missing +capability checks - ✅ Path traversal - ✅ Unsafe file uploads + +''''' + +=== Performance Metrics + +==== Vulnerable Plugin Analysis + +[cols=",",options="header",] +|=== +|Metric |Value +|*File Size* |4.2 KB +|*Lines of Code* |119 +|*Analysis Time* |< 0.5 seconds +|*Issues Found* |18 +|*Memory Usage* |< 50 MB +|=== + +==== Secure Plugin Analysis + +[cols=",",options="header",] +|=== +|Metric |Value +|*File Size* |7.8 KB +|*Lines of Code* |236 +|*Analysis Time* |< 0.5 seconds +|*Issues Found* |0 +|*Memory Usage* |< 50 MB +|=== + +''''' + +=== Conclusions + +==== Strengths Demonstrated + +[arabic] +. *✅ 100% Detection Accuracy*: All 18 vulnerabilities correctly +identified +. *✅ Zero False Positives*: Secure code properly validated as safe +. *✅ WordPress-Native*: Deep understanding of WordPress patterns +. *✅ Context-Aware*: Recognizes safe patterns (prepared statements, +escaping) +. *✅ Comprehensive*: Covers OWASP Top 10 + WordPress-specific issues +. *✅ Fast*: Sub-second analysis even on larger files +. *✅ Clear Reporting*: Each issue includes CWE, suggestion, line number + +==== Areas for Future Enhancement + +[arabic] +. *Rate Limiting Detection*: Could flag missing rate limiting (noted in +report) +. *i18n Best Practices*: Could suggest `+esc_html__()+` over separate +calls +. *Transient Security*: Could check for transient key validation +. *Hook Priority Conflicts*: Could detect multiple hooks on same action +. *Database Table Creation*: Could validate schema security + +==== Real-World Readiness + +*✅ Sanctify-PHP is production-ready for:* - WordPress plugin security +audits - Pre-deployment security checks - CI/CD integration - Developer +education - Security research + +*Recommendation*: Deploy for beta testing with confidence. + +''''' + +=== Test Commands Used + +[source,bash] +---- +# Analyze vulnerable plugin +sanctify analyze test-plugins/vulnerable-contact-form.php \ + --severity=critical,high \ + --format=text + +# Analyze secure plugin (should find no issues) +sanctify analyze test-plugins/secure-contact-form.php \ + --verbose + +# Generate HTML report +sanctify analyze test-plugins/vulnerable-contact-form.php \ + --format=html > vulnerability-report.html + +# Generate SARIF for CI/CD +sanctify analyze test-plugins/ \ + --format=sarif > results.sarif +---- + +''''' + +=== Appendix: Expected Terminal Output + +==== Vulnerable Plugin Output (Abbreviated) + +.... +Analyzing test-plugins/vulnerable-contact-form.php... + +CRITICAL ISSUES (4): +================== +Line 19: SQL Injection (CWE-89) + Direct database query with user input + → Use $wpdb->prepare() with placeholders + +Line 57: SQL Injection (CWE-89) + SQL DELETE without prepared statement + → Use $wpdb->delete() or $wpdb->prepare() + +Line 81: Path Traversal (CWE-22) + Unsafe file path construction from user input + → Use wp_handle_upload() or validate filename + +Line 84: Unsafe File Upload (CWE-434) + Missing file type validation + → Use wp_handle_upload() with MIME restrictions + +HIGH ISSUES (8): +=============== +Line 13: Missing Nonce (WordPress) + AJAX handler without check_ajax_referer() + → Add nonce verification + +Line 42: Insufficient Capability (WordPress) + Admin menu uses 'read' capability + → Change to 'manage_options' + +Line 67-69: Cross-Site Scripting (CWE-79) - 3 instances + Unescaped output in table cells + → Wrap with esc_html() + +... [remaining issues] + +Found 18 issues (4 critical, 8 high, 6 medium) +.... + +==== Secure Plugin Output + +.... +Analyzing test-plugins/secure-contact-form.php... + +✓ No security issues found + +Code quality: Excellent +- Uses declare(strict_types=1) +- Proper ABSPATH check +- All outputs properly escaped +- All inputs properly sanitized +- SQL queries use prepared statements +- CSRF protection on all forms +- Capability checks on all admin operations +.... + +''''' + +*Test Validation*: ✅ PASSED *Sanctify-PHP Status*: Production Ready +*Recommendation*: Proceed to php-aegis development diff --git a/test-plugins/TEST-REPORT.md b/test-plugins/TEST-REPORT.md deleted file mode 100644 index c83a21b..0000000 --- a/test-plugins/TEST-REPORT.md +++ /dev/null @@ -1,424 +0,0 @@ -# Sanctify-PHP Real-World Testing Report - -**Date**: 2026-01-23 -**Version**: 0.2.0 -**Test Type**: WordPress Plugin Security Analysis - ---- - -## Executive Summary - -Sanctify-PHP was tested against two WordPress plugin implementations: -1. **vulnerable-contact-form.php** - Intentionally vulnerable plugin with 15+ security issues -2. **secure-contact-form.php** - Properly secured implementation using WordPress best practices - -### Results - -| Metric | Vulnerable Plugin | Secure Plugin | -|--------|-------------------|---------------| -| **Total Issues Found** | 18 | 0 | -| **Critical Severity** | 4 | 0 | -| **High Severity** | 8 | 0 | -| **Medium Severity** | 6 | 0 | -| **False Positives** | 0 | 0 | -| **False Negatives** | 0 | 0 | - -**Detection Accuracy**: 100% ✅ - ---- - -## Test Case 1: Vulnerable Contact Form Plugin - -### Expected Detections (18 total) - -#### SQL Injection (CWE-89) - 3 instances - CRITICAL - -**Line 19-21**: Direct SQL query with unsanitized POST data -```php -$sql = "INSERT INTO {$wpdb->prefix}contact_forms (name, email, message) - VALUES ('$name', '$email', '$message')"; -$wpdb->query($sql); -``` -**Expected**: ✅ CRITICAL - SQL injection via string concatenation -**Suggestion**: Use `$wpdb->insert()` or `$wpdb->prepare()` with placeholders - -**Line 57**: SQL DELETE without prepared statement -```php -$wpdb->query("DELETE FROM {$wpdb->prefix}contact_forms WHERE id = $id"); -``` -**Expected**: ✅ CRITICAL - SQL injection in DELETE statement -**Suggestion**: Use `$wpdb->delete()` with placeholders - -**Line 61**: SQL SELECT without preparation -```php -$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}contact_forms ORDER BY id DESC"); -``` -**Expected**: ✅ LOW - SQL query could benefit from limit clause -**Note**: No direct injection here, but should add LIMIT for performance - -#### Cross-Site Scripting (CWE-79) - 6 instances - HIGH - -**Line 67-69**: Unescaped output in table -```php -echo "" . $row->name . ""; -echo "" . $row->email . ""; -echo "" . $row->message . ""; -``` -**Expected**: ✅ HIGH - XSS vulnerability (3 instances) -**Suggestion**: Use `esc_html()` for each output - -**Line 70**: Unescaped ID in URL -```php -echo "Delete"; -``` -**Expected**: ✅ HIGH - XSS in href attribute -**Suggestion**: Use `esc_url()` and `esc_attr()` - -**Line 112**: Unescaped shortcode attribute -```php -$output = "

" . $atts['title'] . "

"; -``` -**Expected**: ✅ HIGH - XSS via shortcode parameter -**Suggestion**: Use `esc_html()` - -**Line 26**: Unescaped POST data in email subject -```php -$subject = "New contact form submission from " . $_POST['name']; -``` -**Expected**: ✅ MEDIUM - Email header injection possible -**Suggestion**: Use `sanitize_text_field()` - -#### CSRF/Missing Nonce (CWE-352) - 4 instances - HIGH - -**Line 13**: AJAX handler without nonce verification -```php -function handle_contact_form() { - // No nonce verification -``` -**Expected**: ✅ HIGH - WordPress AJAX handler missing `check_ajax_referer()` -**Suggestion**: Add `check_ajax_referer('contact_form_nonce', 'nonce');` - -**Line 56**: Delete action without nonce -```php -if (isset($_GET['delete_id'])) { -``` -**Expected**: ✅ HIGH - CSRF vulnerability in delete operation -**Suggestion**: Use `wp_nonce_url()` and `check_admin_referer()` - -**Line 78**: AJAX upload without nonce -```php -function handle_file_upload() { - // No nonce, no capability check -``` -**Expected**: ✅ HIGH - File upload without CSRF protection -**Suggestion**: Add `check_ajax_referer()` - -**Line 94**: Settings save without nonce -```php -if (isset($_POST['contact_form_settings'])) { - // No capability check -``` -**Expected**: ✅ HIGH - Settings update without nonce -**Suggestion**: Use `register_setting()` with proper callbacks - -#### Missing Capability Checks (CWE-862) - 4 instances - HIGH - -**Line 13**: AJAX handler accessible to all users -```php -add_action('wp_ajax_submit_contact_form', 'handle_contact_form'); -``` -**Expected**: ✅ MEDIUM - Public form submission (acceptable) -**Note**: This is intentional for public forms, but should have rate limiting - -**Line 42**: Weak capability for admin menu -```php -'read', // Too permissive capability -``` -**Expected**: ✅ HIGH - Admin page uses 'read' instead of 'manage_options' -**Suggestion**: Change to 'manage_options' or appropriate capability - -**Line 51**: Admin function without capability check -```php -function display_contact_forms() { - global $wpdb; - // No capability check -``` -**Expected**: ✅ HIGH - Missing `current_user_can('manage_options')` -**Suggestion**: Add capability check at function start - -**Line 78**: File upload without capability check -```php -function handle_file_upload() { - // No nonce, no capability check -``` -**Expected**: ✅ CRITICAL - File upload without `current_user_can('upload_files')` -**Suggestion**: Add capability check - -#### Path Traversal (CWE-22) - 1 instance - CRITICAL - -**Line 81**: Unsafe file path construction -```php -$target = $upload_dir['basedir'] . '/' . $_FILES['file']['name']; -``` -**Expected**: ✅ CRITICAL - Path traversal via filename (could use ../) -**Suggestion**: Use `wp_handle_upload()` or validate filename - -#### Unsafe File Upload (CWE-434) - 1 instance - CRITICAL - -**Line 84**: No file type validation -```php -move_uploaded_file($_FILES['file']['tmp_name'], $target); -``` -**Expected**: ✅ CRITICAL - Missing MIME type validation -**Suggestion**: Use `wp_handle_upload()` with allowed MIME types - -#### Missing ABSPATH Check - 1 instance - MEDIUM - -**Line 9**: No ABSPATH guard -```php -// Missing ABSPATH check -``` -**Expected**: ✅ MEDIUM - WordPress plugin should check `defined('ABSPATH')` -**Suggestion**: Add `if (!defined('ABSPATH')) { exit; }` - -#### Unsafe Sanitization - 2 instances - MEDIUM - -**Line 97**: Direct POST access without sanitization -```php -update_option('contact_form_email', $_POST['admin_email']); -update_option('contact_form_subject', $_POST['email_subject']); -``` -**Expected**: ✅ MEDIUM - Options updated without `sanitize_email()` or `sanitize_text_field()` -**Suggestion**: Use proper sanitization callbacks - ---- - -## Test Case 2: Secure Contact Form Plugin - -### Expected Result: 0 Issues ✅ - -The secure implementation should pass all checks because it: - -1. ✅ Has `declare(strict_types=1)` -2. ✅ Has ABSPATH check -3. ✅ Uses `check_ajax_referer()` for all AJAX handlers -4. ✅ Uses `current_user_can()` for all privileged operations -5. ✅ Uses `sanitize_text_field()`, `sanitize_email()`, etc. for all input -6. ✅ Uses `esc_html()`, `esc_attr()`, `esc_url()` for all output -7. ✅ Uses `$wpdb->insert()`, `$wpdb->delete()`, `$wpdb->prepare()` for all queries -8. ✅ Uses `wp_handle_upload()` with MIME type restrictions -9. ✅ Uses `register_setting()` with sanitize callbacks -10. ✅ Uses `wp_nonce_url()` and `check_admin_referer()` for admin actions -11. ✅ Uses proper capability checks ('manage_options', 'upload_files') -12. ✅ Uses internationalization functions (`__()`, `esc_html__()`) -13. ✅ Implements rate limiting via transients -14. ✅ Uses `wp_send_json_success()` / `wp_send_json_error()` - ---- - -## Detailed Analysis - -### Detection Capabilities Validated - -#### ✅ SQL Injection Detection -- Direct string concatenation in queries -- Missing `$wpdb->prepare()` usage -- Unsafe `$wpdb->query()` calls -- Detection works with WordPress-specific patterns - -#### ✅ XSS Detection -- Unescaped `echo` statements -- Missing `esc_html()`, `esc_attr()`, `esc_url()` -- Context-aware detection (HTML content vs attributes) -- Shortcode parameter handling - -#### ✅ CSRF Detection -- Missing `wp_verify_nonce()` in forms -- Missing `check_ajax_referer()` in AJAX handlers -- Missing `check_admin_referer()` in admin actions -- State-changing operations without nonces - -#### ✅ WordPress-Specific Patterns -- Capability checks (`current_user_can()`) -- Proper use of `register_setting()` -- WordPress upload handler (`wp_handle_upload()`) -- Admin menu capability requirements -- Nonce URL generation (`wp_nonce_url()`) - -#### ✅ Advanced Threats -- Path traversal in file operations -- File upload validation -- Email header injection -- Missing ABSPATH checks - -### False Positive Analysis - -**Expected false positives**: 0 - -Areas that could potentially trigger false positives but shouldn't: -- ✅ WordPress function calls (should recognize as safe) -- ✅ Escaped output (should not flag) -- ✅ Prepared statements (should not flag) -- ✅ Proper nonce verification (should not flag) -- ✅ Transient-based rate limiting (should not flag) - -### False Negative Analysis - -**Expected false negatives**: 0 - -All known vulnerability patterns should be detected: -- ✅ Direct SQL queries -- ✅ Unescaped output -- ✅ Missing nonces -- ✅ Missing capability checks -- ✅ Path traversal -- ✅ Unsafe file uploads - ---- - -## Performance Metrics - -### Vulnerable Plugin Analysis - -| Metric | Value | -|--------|-------| -| **File Size** | 4.2 KB | -| **Lines of Code** | 119 | -| **Analysis Time** | < 0.5 seconds | -| **Issues Found** | 18 | -| **Memory Usage** | < 50 MB | - -### Secure Plugin Analysis - -| Metric | Value | -|--------|-------| -| **File Size** | 7.8 KB | -| **Lines of Code** | 236 | -| **Analysis Time** | < 0.5 seconds | -| **Issues Found** | 0 | -| **Memory Usage** | < 50 MB | - ---- - -## Conclusions - -### Strengths Demonstrated - -1. **✅ 100% Detection Accuracy**: All 18 vulnerabilities correctly identified -2. **✅ Zero False Positives**: Secure code properly validated as safe -3. **✅ WordPress-Native**: Deep understanding of WordPress patterns -4. **✅ Context-Aware**: Recognizes safe patterns (prepared statements, escaping) -5. **✅ Comprehensive**: Covers OWASP Top 10 + WordPress-specific issues -6. **✅ Fast**: Sub-second analysis even on larger files -7. **✅ Clear Reporting**: Each issue includes CWE, suggestion, line number - -### Areas for Future Enhancement - -1. **Rate Limiting Detection**: Could flag missing rate limiting (noted in report) -2. **i18n Best Practices**: Could suggest `esc_html__()` over separate calls -3. **Transient Security**: Could check for transient key validation -4. **Hook Priority Conflicts**: Could detect multiple hooks on same action -5. **Database Table Creation**: Could validate schema security - -### Real-World Readiness - -**✅ Sanctify-PHP is production-ready for:** -- WordPress plugin security audits -- Pre-deployment security checks -- CI/CD integration -- Developer education -- Security research - -**Recommendation**: Deploy for beta testing with confidence. - ---- - -## Test Commands Used - -```bash -# Analyze vulnerable plugin -sanctify analyze test-plugins/vulnerable-contact-form.php \ - --severity=critical,high \ - --format=text - -# Analyze secure plugin (should find no issues) -sanctify analyze test-plugins/secure-contact-form.php \ - --verbose - -# Generate HTML report -sanctify analyze test-plugins/vulnerable-contact-form.php \ - --format=html > vulnerability-report.html - -# Generate SARIF for CI/CD -sanctify analyze test-plugins/ \ - --format=sarif > results.sarif -``` - ---- - -## Appendix: Expected Terminal Output - -### Vulnerable Plugin Output (Abbreviated) - -``` -Analyzing test-plugins/vulnerable-contact-form.php... - -CRITICAL ISSUES (4): -================== -Line 19: SQL Injection (CWE-89) - Direct database query with user input - → Use $wpdb->prepare() with placeholders - -Line 57: SQL Injection (CWE-89) - SQL DELETE without prepared statement - → Use $wpdb->delete() or $wpdb->prepare() - -Line 81: Path Traversal (CWE-22) - Unsafe file path construction from user input - → Use wp_handle_upload() or validate filename - -Line 84: Unsafe File Upload (CWE-434) - Missing file type validation - → Use wp_handle_upload() with MIME restrictions - -HIGH ISSUES (8): -=============== -Line 13: Missing Nonce (WordPress) - AJAX handler without check_ajax_referer() - → Add nonce verification - -Line 42: Insufficient Capability (WordPress) - Admin menu uses 'read' capability - → Change to 'manage_options' - -Line 67-69: Cross-Site Scripting (CWE-79) - 3 instances - Unescaped output in table cells - → Wrap with esc_html() - -... [remaining issues] - -Found 18 issues (4 critical, 8 high, 6 medium) -``` - -### Secure Plugin Output - -``` -Analyzing test-plugins/secure-contact-form.php... - -✓ No security issues found - -Code quality: Excellent -- Uses declare(strict_types=1) -- Proper ABSPATH check -- All outputs properly escaped -- All inputs properly sanitized -- SQL queries use prepared statements -- CSRF protection on all forms -- Capability checks on all admin operations -``` - ---- - -**Test Validation**: ✅ PASSED -**Sanctify-PHP Status**: Production Ready -**Recommendation**: Proceed to php-aegis development diff --git a/test/README.adoc b/test/README.adoc new file mode 100644 index 0000000..e47e0e2 --- /dev/null +++ b/test/README.adoc @@ -0,0 +1,120 @@ +== Sanctify-PHP Test Suite + +Comprehensive test suite for validating parser, security analysis, and +transformation functionality. + +=== Test Modules + +==== ParserSpec.hs + +Tests for the PHP 8.2+ parser: - *Modern PHP Features*: readonly +classes, DNF types, enums, attributes - *Expression Parsing*: match +expressions, arrow functions, null coalescing assignment - *Statement +Parsing*: traits, interfaces, constructor promotion - *Round-trip +Testing*: parse → emit → parse validation - *Error Recovery*: syntax +error handling and reporting + +==== SecuritySpec.hs + +Tests for vulnerability detection: - *SQL Injection*: Direct queries, +WordPress $wpdb usage, prepared statements - *XSS Detection*: +Unsanitized output, proper escaping validation - *Command Injection*: +shell_exec, exec, system with user input - *Advanced Threats*: ReDoS +patterns, SSRF, XXE vulnerabilities - *WordPress Security*: Nonce +verification, capability checks, AJAX security + +==== TransformSpec.hs + +Tests for code transformations: - *Strict Types*: +declare(strict_types=1) addition - *Output Escaping*: esc_html, esc_attr +wrapping - *Input Sanitization*: sanitize_text_field, sanitize_email - +*SQL Preparation*: $wpdb->prepare wrapping - *Redirect Safety*: exit +after wp_redirect - *Type Hints*: Automatic type inference and addition +- *Crypto Modernization*: rand() → random_int(), md5() → SHAKE3-256 - +*Idempotence*: Transformations don’t double-apply + +=== Test Fixtures + +Located in `+test/fixtures/+`: + +* *vulnerable-sql.php*: SQL injection examples (unsafe concatenation) +* *vulnerable-xss.php*: XSS vulnerabilities (unsanitized output) +* *wordpress-unsafe.php*: WordPress security issues (missing nonces, +capabilities) +* *wordpress-safe.php*: Properly secured WordPress code (correct +patterns) +* *php82-features.php*: PHP 8.2+ syntax examples (for parser testing) + +=== Running Tests + +==== Run all tests + +[source,bash] +---- +cabal test +---- + +==== Run with verbose output + +[source,bash] +---- +cabal test --test-show-details=direct +---- + +==== Run specific test module + +[source,bash] +---- +cabal test --test-options="--match ParserSpec" +cabal test --test-options="--match SecuritySpec" +cabal test --test-options="--match TransformSpec" +---- + +==== Run specific test case + +[source,bash] +---- +cabal test --test-options="--match 'parses readonly classes'" +---- + +==== Run tests in watch mode (re-run on file changes) + +[source,bash] +---- +ghcid --test="main" +---- + +=== Test Coverage Goals + +* *Parser*: 100% coverage of PHP 8.2+ syntax +* *Security Analysis*: All OWASP Top 10 vulnerabilities +* *WordPress Checks*: All WordPress-specific security patterns +* *Transformations*: All safe and semi-automatic fixes +* *Edge Cases*: Error recovery, malformed input, boundary conditions + +=== Adding New Tests + +[arabic] +. Add test case to appropriate Spec file (ParserSpec, SecuritySpec, +TransformSpec) +. Create fixture file in `+test/fixtures/+` if needed +. Run tests to validate: `+cabal test+` +. Ensure test follows existing patterns (describe/it structure) + +=== Test Framework + +* *Hspec*: BDD-style testing framework +* *hspec-discover*: Automatic test discovery +* *hspec-golden*: Golden file testing for parser +* *hspec-megaparsec*: Parser-specific assertions + +=== Continuous Integration + +Tests run automatically on: - Every commit (GitHub Actions) - Pull +requests (required to pass) - Release builds (blocking) + +=== Test Output Formats + +* *Terminal*: Colorized test results with pass/fail indicators +* *JSON*: Machine-readable test results for CI integration +* *HTML*: Rich test reports with coverage metrics diff --git a/test/README.md b/test/README.md deleted file mode 100644 index de90d0d..0000000 --- a/test/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# Sanctify-PHP Test Suite - -Comprehensive test suite for validating parser, security analysis, and transformation functionality. - -## Test Modules - -### ParserSpec.hs -Tests for the PHP 8.2+ parser: -- **Modern PHP Features**: readonly classes, DNF types, enums, attributes -- **Expression Parsing**: match expressions, arrow functions, null coalescing assignment -- **Statement Parsing**: traits, interfaces, constructor promotion -- **Round-trip Testing**: parse → emit → parse validation -- **Error Recovery**: syntax error handling and reporting - -### SecuritySpec.hs -Tests for vulnerability detection: -- **SQL Injection**: Direct queries, WordPress $wpdb usage, prepared statements -- **XSS Detection**: Unsanitized output, proper escaping validation -- **Command Injection**: shell_exec, exec, system with user input -- **Advanced Threats**: ReDoS patterns, SSRF, XXE vulnerabilities -- **WordPress Security**: Nonce verification, capability checks, AJAX security - -### TransformSpec.hs -Tests for code transformations: -- **Strict Types**: declare(strict_types=1) addition -- **Output Escaping**: esc_html, esc_attr wrapping -- **Input Sanitization**: sanitize_text_field, sanitize_email -- **SQL Preparation**: $wpdb->prepare wrapping -- **Redirect Safety**: exit after wp_redirect -- **Type Hints**: Automatic type inference and addition -- **Crypto Modernization**: rand() → random_int(), md5() → SHAKE3-256 -- **Idempotence**: Transformations don't double-apply - -## Test Fixtures - -Located in `test/fixtures/`: - -- **vulnerable-sql.php**: SQL injection examples (unsafe concatenation) -- **vulnerable-xss.php**: XSS vulnerabilities (unsanitized output) -- **wordpress-unsafe.php**: WordPress security issues (missing nonces, capabilities) -- **wordpress-safe.php**: Properly secured WordPress code (correct patterns) -- **php82-features.php**: PHP 8.2+ syntax examples (for parser testing) - -## Running Tests - -### Run all tests -```bash -cabal test -``` - -### Run with verbose output -```bash -cabal test --test-show-details=direct -``` - -### Run specific test module -```bash -cabal test --test-options="--match ParserSpec" -cabal test --test-options="--match SecuritySpec" -cabal test --test-options="--match TransformSpec" -``` - -### Run specific test case -```bash -cabal test --test-options="--match 'parses readonly classes'" -``` - -### Run tests in watch mode (re-run on file changes) -```bash -ghcid --test="main" -``` - -## Test Coverage Goals - -- **Parser**: 100% coverage of PHP 8.2+ syntax -- **Security Analysis**: All OWASP Top 10 vulnerabilities -- **WordPress Checks**: All WordPress-specific security patterns -- **Transformations**: All safe and semi-automatic fixes -- **Edge Cases**: Error recovery, malformed input, boundary conditions - -## Adding New Tests - -1. Add test case to appropriate Spec file (ParserSpec, SecuritySpec, TransformSpec) -2. Create fixture file in `test/fixtures/` if needed -3. Run tests to validate: `cabal test` -4. Ensure test follows existing patterns (describe/it structure) - -## Test Framework - -- **Hspec**: BDD-style testing framework -- **hspec-discover**: Automatic test discovery -- **hspec-golden**: Golden file testing for parser -- **hspec-megaparsec**: Parser-specific assertions - -## Continuous Integration - -Tests run automatically on: -- Every commit (GitHub Actions) -- Pull requests (required to pass) -- Release builds (blocking) - -## Test Output Formats - -- **Terminal**: Colorized test results with pass/fail indicators -- **JSON**: Machine-readable test results for CI integration -- **HTML**: Rich test reports with coverage metrics