userfrosting/fortress
最新稳定版本:4.5.0
Composer 安装命令:
composer require userfrosting/fortress
包简介
A PHP library for whitelisting, validating, and canonicalizing HTTP request data against a JSON Schema
README 文档
README
| Branch | Build | Coverage | Style |
|---|---|---|---|
| master | |||
| develop | |
If you simply want to show that you like this project, or want to remember it for later, you should star, not fork, this repository. Forking is only for when you are ready to create your own copy of the code to work on.
By Alex Weissman
Copyright (c) 2015-2019
A schema-driven system for elegant whitelisting, transformation and validation of user input on both the client and server sides from a unified set of rules.
Introduction
Data from the outside world is the Achilles' heel of modern interactive web services and applications. Code injection, cross-site scripting (XSS), CSRF, and many other types of malicious attacks are successful when a web application accepts user input that it shouldn't have, or fails to neutralize the damaging parts of the input. Even non-malicious users can inadvertently submit something that breaks your web service, causing it to behave in some unexpected way.
For the sake of both security and quality user experience, it is important for a web developer to do two things:
- Decide exactly what type of input your application should accept, and;
- Decide how your application should behave when it receives something that violates those rules.
Sounds simple, right? Unfortunately, even experienced developers often slip up, allowing a malicious user to execute SQL or PHP on the application's server (or, in the case of XSS and CSRF attacks, allow a user to trick other users into executing malicious code).
Part of the problem is that this kind of filtering must be done at every point in the application where the user can submit raw data to the server. A modern web application might accept hundreds of different types of POST requests, and it can become extremely tedious to code the rules for each request manually. Much of this work must also be done on both the client side (for user experience) and the server side (for security).
Fortress solves this problem by providing a uniform interface for validating raw user input on both the client side (in Javascript) and on the server side (in PHP) using a single unified set of rules. All you have to do is create a request schema, which defines what fields you're expecting the user to submit, and rules for how to handle the contents of those fields. For example, you might want to check that an email address is well-formed. The request schema, which is simply a YAML or JSON document, makes it easy to manipulate these rules in one place.
The request schema can be applied on the server side to received request data, but also be transformed to formats compatible with client-side validation libraries such as the jQuery Validation plugin, making it easy to perform client- and server-side validation without having to write every rule twice.
An example request schema, written using the WDVSS standard:
schema.yaml
name:
validators:
length:
min: 1
max: 200
message: Please enter a name between 1 and 200 characters.
required :
message : Please specify your name.
email:
validators:
required:
message: Please specify your email address.
length:
min: 1
max: 150
message: Please enter an email address between 1 and 150 characters.
email:
message : That does not appear to be a valid email address.
message:
validators:
required:
message: Please enter a message
Dependencies
- PHP 5.6+
- Valitron (server-side validation)
- HTML Purifier
- Symfony YAML Parser
- userfrosting/i18n
- userfrosting/support
Installation
To install with composer:
- If you haven't already, get Composer and install it - preferably, globally.
- Require Fortress, either by running
php composer.phar require alexweissman/fortress, or by creating acomposer.jsonfile:
{
"require": {
"php": ">=5.6.0",
"userfrosting/fortress": "^4.2.0"
}
}
and running composer install.
- Include the
vendor/autoload.phpfile in your project:
require dirname(__DIR__) . '/vendor/autoload.php';
Usage
Request schema
To read a YAML or JSON schema, use a YamlFileLoader:
$loader = new \UserFrosting\Support\Repository\Loader\YamlFileLoader('schema/forms/contact.yaml');
To use it, it must be read and loaded into a RequestSchemaRepository object:
$schema = new \UserFrosting\Fortress\RequestSchema\RequestSchemaRepository($loader->load());
You can add additional validation rules to a schema at runtime, if you wish:
$schema->addValidator("puppies", "required");
$schema->addValidator("minions", "range", [
"min" => 0,
"max" => 20,
"message" => "Not enough minions"
]);
$schema->addValidator("email", "length", [
"min" => 1,
"max" => 100,
"message" => "ACCOUNT_EMAIL_CHAR_LIMIT"
]);
Data transformation
The data transformer performs the following tasks:
- Whitelisting of input array against the schema. By default, any parameters not listed in the schema will be filtered out. Other options are "error" and "skip".
- Perform a series of transformations on the input data. For example,
trimorpurify. - Set any default values for fields in the schema which are not present in the input array.
$post = [
"puppies" => "<script>I'm definitely really a puppy </script>0 ",
"horses" => "seven pretty horses"
];
$transformer = new \UserFrosting\Fortress\RequestDataTransformer($schema);
// Transform, and print transformed data for demo purposes
$transformedData = $transformer->transform($post, "skip");
echo "<h2>Transformed data</h2>";
echo "<pre>";
print_r($transformedData);
echo "</pre>";
Server-side data validation
To process an array of user input, create a ServerSideValidator object with the schema and a translator object.
Translator object
Fortress requires a Translator (see i18n) object to translate message keys that may appear in rules:
$locale = new \UserFrosting\I18n\Locale('en_US');
$dictionary = new \UserFrosting\I18n\Dictionary($locale, $this->ci->locator);
$translator = new \UserFrosting\I18n\Translator($dictionary);
Then, call validate on the input array. validate will return false if any of the rules are failed. Call errors to get the list of generated error messages. You might want to store these error messages to a flash messaging system so they can be shown to the user.
$validator = new \UserFrosting\Fortress\ServerSideValidator($schema, $translator);
if (!$validator->validate($transformedData)) {
echo "<h2>Validation results</h2>";
echo "<pre>";
print_r($validator->errors());
echo "</pre>";
}
Client-side data validation
When generating a page or form, you will use one of the Adapter classes to generate a compatible set of rules from your WDVSS schema:
// Test client validators
$clientVal = new \UserFrosting\Fortress\Adapter\JqueryValidationAdapter($schema, $translator);
echo "<h2>Client-side validation schema (JSON)</h2>";
echo "<pre>";
print_r($clientVal->rules());
echo "</pre>";
Add Namespace to the validation field names
You can also add an array prefix to the field names to generate validation rules for the input schema that will wrap all the field names with the namespace of the form for which the validation rules are being generated.
// Test client validators
$clientVal = new \UserFrosting\Fortress\Adapter\JqueryValidationAdapter($schema, $translator);
echo "<h2>Client-side validation schema (JSON)</h2>";
echo "<pre>";
print_r($clientVal->rules('json',false,'mycoolform1'));
echo "</pre>";
This will generate validation rules with field names mycoolform1[<fieldname>] : { .... } instead of <fieldname> : { .... }
This comes in handy when you are generating validation rules for multiple forms or form sections on the same page
Message keys
The message for a rule can be either a plain string, or a translatable message key.
In the definitions of translatable message keys, the keyword "self" is reserved to refer to the name of the field being validated. Thus, a message like this:
"MIN_LENGTH" => "The field '{{self}}' must be at least {{min}} characters long"
for a field defined as:
tagline:
validators:
length:
min: 10
message: MIN_LENGTH
Would translate to:
"The field 'tagline' must be at least 10 characters long"
Limit rules to server or client only
Sometimes, you only want a validation rule to be applied server-side but not in Javascript on the client side, or vice versa. For example, there may be forms that contain hidden data that needs to be validated on the server-side, but is not directly manipulated by the user in the browser. Thus, these fields would not need client-side validation rules.
Alternatively, there might be fields that appear in the form that should be validated for the sake of user experience, but are not actually used by (or even sent to) the server.
To accomplish this, each validation rule can now accept a domain property. Setting to "server" will have it only applied server-side. Setting to "client" will have it only appear in the client-side rules. If not specified, rules will be applied both server- and client-side by default. You can also set this explicitly with the value "both".
Style Guide
Testing
userfrosting/fortress 适用场景与选型建议
userfrosting/fortress 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 49.49k 次下载、GitHub Stars 达 25, 最近一次更新时间为 2016 年 03 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validation」 「transformation」 「userfrosting」 「whitelisting」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 userfrosting/fortress 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 userfrosting/fortress 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 userfrosting/fortress 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A secure, modern user management system for PHP.
Transform data for serialization
Form generator for UserFrosting V5
Adds request-parameter validation to the SLIM 3.x PHP framework
Cs2cs wrapper for PHP
Breadcrumb service provider for UserFrosting V4
统计信息
- 总下载量: 49.49k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 25
- 点击次数: 32
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2016-03-29