定制 hk2/sanitize-search 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

hk2/sanitize-search

Composer 安装命令:

composer require hk2/sanitize-search

包简介

Magento 2 extension to sanitize harmful SQL keywords from search queries

README 文档

README

Version Magento PHP License Packagist
Website LinkedIn Email

HK2 Sanitize Search — Magento 2 Search Query Sanitizer

HK2 SanitizeSearch is a lightweight Magento 2 module that sanitizes user-submitted search queries by stripping harmful SQL keywords and characters. It hooks into Magento\Search\Model\QueryFactory via a beforeCreate plugin, applies a regex filter, and logs sanitization events to a dedicated log file for auditing.

📄 Overview

The module acts as a defense-in-depth layer against SQL injection attempts entering through the storefront search box. It removes SQL control keywords (SELECT, INSERT, UPDATE, DELETE, DROP, UNION), statement terminators (;), and comment markers (--, #) from user input before it reaches the search pipeline. Clean queries pass through with zero overhead.

🧠 Problem Statement

Magento's native search accepts arbitrary user input and feeds it into the search query pipeline. While Magento uses prepared statements and proper ORM practices, an unsanitized search box represents an unnecessary attack surface. Malicious actors can probe the system by submitting search strings containing SQL control characters and keywords (e.g., SELECT, UNION, ;, --).

Security best practices dictate that user input should be sanitized at every trust boundary. The search input field — accessible to any visitor — is a clear trust boundary that benefits from proactive sanitization.

💡 Solution Approach

A plugin intercepts the beforeCreate method of Magento\Search\Model\QueryFactory and applies a preg_replace to remove dangerous patterns from the raw query string:

  • SQL keywords: SELECT, INSERT, UPDATE, DELETE, DROP, UNION (case-insensitive)
  • Statement terminator: ;
  • SQL comment markers: -- and #

If any content is stripped, the event is logged to var/log/sanitizer.log at WARNING level. The sanitizer can be toggled on/off via admin configuration at Stores > Configuration > HK2 > Search Sanitizer.

🆚 Alternatives Considered

Approach Why not chosen
Prepared statement reliance only Places full trust in the ORM layer; no defense-in-depth at the input boundary
Full input validation/whitelisting Too restrictive; would break legitimate search queries with special characters
WAF-level filtering Requires external infrastructure; adds latency; harder to audit
Escaping instead of stripping Escaped SQL keywords may still appear suspicious in logs or trigger false alarms
Third-party security module Heavy dependency; most include far more than search sanitization

Stripping is chosen as a minimal, predictable operation — it removes known dangerous patterns without altering the shape of legitimate queries.

👥 Who is this for?

  • Magento 2 store owners hardening their storefront against SQL injection probes
  • Security-conscious developers needing a zero-dependency, auditable sanitization layer
  • Agencies and system integrators deploying sites that must pass security compliance reviews
  • Merchants in regulated industries (finance, healthcare, e-commerce) with customer data behind the search interface

🎯 Use Cases

  1. E-commerce stores — prevent SQL injection attempts through the product search box
  2. Multi-tenant Magento installations — a vulnerability in one tenant's code could be probed via search
  3. Compliance-driven environments — satisfying audit requirements for input sanitization at all user entry points
  4. Staging/demo sites — quickly add a security layer without modifying core or installing a full security suite
  5. Custom search implementations — where Magento\Search\Model\QueryFactory is still part of the pipeline

✨ Key Features

  • SQL keyword stripping — removes SELECT, INSERT, UPDATE, DELETE, DROP, UNION, ;, --, and # from search queries (case-insensitive)
  • Dedicated logging — every sanitization event is recorded to var/log/sanitizer.log at WARNING level with original and sanitized values
  • Configurable enable/disable — toggle via Stores > Configuration > HK2 > Search Sanitizer
  • Defense-in-depth — complements Magento's ORM and prepared statements with input-level sanitization
  • Zero impact on clean queries — queries without harmful patterns pass through unmodified
  • Lightweight — single plugin, no database schemas, no API endpoints, no console commands

🏗️ Architecture Overview

┌─────────────────────────────────────────────────────────────────────────┐
│  Storefront search form                                                │
│  User submits:  "product; DROP TABLE customers; --"                    │
└──────────────────────────┬──────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────────────────┐
│  Magento\Search\Model\QueryFactory::beforeCreate                       │
│  (Plugin: HK2\SanitizeSearch\Plugin\SearchSanitizer)                   │
│                                                                         │
│  1. Check config flag (hk2_sanitizesearch/general/enabled)             │
│  2. If disabled → return original query unchanged                       │
│  3. If enabled:                                                         │
│     a. preg_replace(/(select|insert|update|delete|drop|union|;|--|#)/i) │
│     b. trim()                                                           │
│     c. If changed → log original + sanitized to Monolog (WARNING)      │
│     d. Return sanitized query                                           │
└─────────────────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────────────────┐
│  Normal Magento search pipeline                                        │
│  (Query, search results, etc.)                                          │
└─────────────────────────────────────────────────────────────────────────┘

Logging (when change detected):
    HK2\SanitizeSearch\Logger\Logger (custom Monolog channel)
        └── HK2\SanitizeSearch\Logger\Handler (writes to var/log/sanitizer.log, WARNING level)

Key files

File Role
Plugin/SearchSanitizer.php Plugin intercepting QueryFactory::beforeCreate
Logger/Logger.php Custom Monolog logger class
Logger/Handler.php Log handler writing to var/log/sanitizer.log
etc/di.xml Plugin registration and logger wiring
etc/module.xml Module declaration sequencing on HK2_Core
etc/adminhtml/system.xml Admin system configuration under HK2 tab
etc/adminhtml/menu.xml Admin menu entry under Content

📋 System Requirements

  • Magento: 2.4.x (Open Source / Adobe Commerce)
  • PHP: ^8.1 || ^8.2 || ^8.3 || ^8.4
  • Composer: 2.x
  • Dependencies: hk2/core ^1.0, magento/framework ^103.0.0
  • No database modifications — operates entirely at the PHP plugin layer

🚀 Installation

composer require hk2/sanitize-search
bin/magento module:enable HK2_SanitizeSearch
bin/magento setup:upgrade
bin/magento cache:clean

Verify:

bin/magento module:status HK2_SanitizeSearch

⚙️ Configuration

Navigate to Stores > Configuration > HK2 > Search Sanitizer (or Content > Search Sanitizer from the admin menu).

Setting Description
Enable Search Sanitization Set to Yes to enable SQL keyword stripping. Set to No to pass all queries through unchanged.

Default: No (disabled). Ships disabled so operators can enable after testing.

Configuration path: hk2_sanitizesearch/general/enabled

🔒 Content Security Policy (CSP)

This module does not modify Magento's CSP headers or csp_whitelist.xml. It operates exclusively at the server-side PHP layer before the search query enters the ORM pipeline.

HK2 SanitizeSearch complements CSP in a holistic security strategy: CSP prevents malicious scripts from executing in the browser, while search sanitization prevents malicious SQL patterns from entering the database pipeline.

🚀 Production Readiness

This module is production-ready and has been designed with the following considerations:

  • Zero database schema changes — no setup patch, no SQL install/upgrade scripts, no data patches
  • Zero API surface — no REST, GraphQL, or SOAP endpoints to secure
  • Minimal performance impact — a single preg_replace on the search query string; disabled by default
  • Configurable at runtime — toggle via admin configuration without code deployment
  • Defense-in-depth — complements existing Magento security layers rather than replacing them
  • Auditable — all sanitization events are logged with original and sanitized values for forensic review

Enable on staging first, test with your store's typical search patterns, then enable in production.

🔐 Privacy & GDPR

  • No personal data collection — the module does not track, store, or transmit user identities, IP addresses, or session data
  • Log contents — the only persisted data is the original and sanitized query string (written to var/log/sanitizer.log at WARNING level)
  • Log retention — standard Magento log rotation applies; configure per your data protection obligations
  • No third-party services — the module makes no external network calls and sends no data off-server
  • Recommended actions: review log retention for var/log/sanitizer.log, consider disabling query logging if searches may contain PII, include sanitization logging in your data processing register

🧪 Testing Strategy

Test case Input Expected output
Clean query laptop laptop (unchanged, no log)
SQL keyword SELECT * FROM users * FROM users (logged)
Statement terminator admin'; DELETE admin'' (logged)
Comment marker password-- comment password comment (logged)
Hash comment admin#foo adminfoo (logged)
Mixed case UnIoN Select 1 1 (logged)
Multiple keywords DROP;SELECT;UPDATE `` (empty, logged)
Disabled module any input with config disabled unchanged, no log
Empty input `` `` (no error)

Recommended approach: enable on a staging environment first, submit various test queries, and inspect var/log/sanitizer.log before enabling in production.

No automated test suite ships with the module.

📚 Documentation

Additional documentation is available in the docs/ directory:

⚠️ Known Limitations

  1. Pattern-based, not context-aware — the regex match removes substrings. "selective" becomes "ive". This is by design: the filter errs on the side of removing potential threats.
  2. Defense-in-depth, not primary SQL protection — not a substitute for prepared statements, parameterized queries, or proper ORM usage.
  3. No Unicode / multibyte awareness — non-ASCII homoglyph attacks are not detected.
  4. Log growth — in high-traffic stores with aggressive probing, the log file may grow quickly.

🤝 Contributing

Contributions are welcome. Please open an issue or pull request on the GitHub repository.

All contributions must adhere to the Conventional Commits specification for automated semantic release.

📄 License

Licensed under the Open Software License 3.0 (OSL-3.0).

The OSL-3.0 is an OSI-approved open source license. It allows you to use, modify, and distribute this software, provided that distributed modifications are made available in source code form.

⚖️ Disclaimer

This module provides defense-in-depth sanitization and is not a replacement for secure coding practices. The author and Basant Mandal are not responsible for any damages or security breaches resulting from the use or misuse of this software. Always follow Magento security best practices, keep your installation up to date, and perform regular security audits.

hk2/sanitize-search 适用场景与选型建议

hk2/sanitize-search 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 05 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「magento2」 「magento-module」 「HK2」 「Basant Mandal」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 hk2/sanitize-search 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 hk2/sanitize-search 我们能提供哪些服务?
定制开发 / 二次开发

基于 hk2/sanitize-search 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 22
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: OSL-3.0
  • 更新时间: 2026-05-11