SecurityComponent
extends Component
in package
The Security Component creates an easy way to integrate tighter security in your application. It provides methods for these tasks:
- Form tampering protection.
- Requiring that SSL be used.
Tags
Table of Contents
Constants
- DEFAULT_EXCEPTION_MESSAGE = 'The request has been black-holed'
- Default message used for exceptions thrown
Properties
- $_action : string
- Holds the current action of the controller
- $_componentMap : array<string, array<string|int, mixed>>
- A component lookup table used to lazy load component objects.
- $_config : array<string, mixed>
- Runtime config
- $_configInitialized : bool
- Whether the config property has already been configured with defaults
- $_defaultConfig : array<string, mixed>
- Default config
- $_registry : ComponentRegistry
- Component registry class used to lazy load components.
- $components : array<string|int, mixed>
- Other Components this component uses.
Methods
- __construct() : mixed
- Constructor
- __debugInfo() : array<string, mixed>
- Returns an array that can be used to describe the internal state of this object.
- __get() : Component|null
- Magic method for lazy loading $components.
- blackHole() : mixed
- Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error
- configShallow() : $this
- Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
- generateToken() : ServerRequest
- Manually add form tampering prevention token information into the provided request object.
- getConfig() : mixed
- Returns the config.
- getConfigOrFail() : mixed
- Returns the config for this specific key.
- getController() : Controller
- Get the controller this component is bound to.
- implementedEvents() : array<string, mixed>
- Events supported by this component.
- initialize() : void
- Constructor hook method.
- log() : bool
- Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
- requireSecure() : void
- Sets the actions that require a request that is SSL-secured, or empty for all actions
- setConfig() : $this
- Sets the config.
- startup() : Response|null
- Component startup. All security checking happens here.
- _callback() : mixed
- Calls a controller callback method
- _configDelete() : void
- Deletes a single config key.
- _configRead() : mixed
- Reads a config key.
- _configWrite() : void
- Writes a config key.
- _debugCheckFields() : array<string|int, string>
- Iterates data array to check against expected
- _debugExpectedFields() : string|null
- Generate debug message for the expected fields
- _debugPostTokenNotMatching() : string
- Create a message for humans to understand why Security token is not matching
- _fieldsList() : array<string|int, mixed>
- Return the fields list for the hash calculation
- _hashParts() : array<string|int, string>
- Return hash parts for the Token generation
- _matchExistingFields() : array<string|int, string>
- Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
- _secureRequired() : void
- Check if access requires secure connection
- _sortedUnlocked() : string
- Get the sorted unlocked string
- _throwException() : void
- Check debug status and throw an Exception based on the existing one
- _unlocked() : string
- Get the unlocked string
- _validatePost() : void
- Validate submitted form
- _validToken() : string
- Check if token is valid
Constants
DEFAULT_EXCEPTION_MESSAGE
Default message used for exceptions thrown
public
string
DEFAULT_EXCEPTION_MESSAGE
= 'The request has been black-holed'
Properties
$_action
Holds the current action of the controller
protected
string
$_action
$_componentMap
A component lookup table used to lazy load component objects.
protected
array<string, array<string|int, mixed>>
$_componentMap
= []
$_config
Runtime config
protected
array<string, mixed>
$_config
= []
$_configInitialized
Whether the config property has already been configured with defaults
protected
bool
$_configInitialized
= false
$_defaultConfig
Default config
protected
array<string, mixed>
$_defaultConfig
= ['blackHoleCallback' => null, 'requireSecure' => [], 'unlockedFields' => [], 'unlockedActions' => [], 'validatePost' => true]
-
blackHoleCallback
- The controller method that will be called if this request is black-hole'd. -
requireSecure
- List of actions that require an SSL-secured connection. -
unlockedFields
- Form fields to exclude from POST validation. Fields can be unlocked either in the Component, or with FormHelper::unlockField(). Fields that have been unlocked are not required to be part of the POST and hidden unlocked fields do not have their values checked. -
unlockedActions
- Actions to exclude from POST validation checks. Other checks like requireSecure() etc. will still be applied. -
validatePost
- Whether to validate POST data. Set to false to disable for data coming from 3rd party services, etc.
$_registry
Component registry class used to lazy load components.
protected
ComponentRegistry
$_registry
$components
Other Components this component uses.
protected
array<string|int, mixed>
$components
= []
Methods
__construct()
Constructor
public
__construct(ComponentRegistry $registry[, array<string, mixed> $config = [] ]) : mixed
Parameters
- $registry : ComponentRegistry
-
A component registry this component can use to lazy load its components.
- $config : array<string, mixed> = []
-
Array of configuration settings.
__debugInfo()
Returns an array that can be used to describe the internal state of this object.
public
__debugInfo() : array<string, mixed>
Return values
array<string, mixed>__get()
Magic method for lazy loading $components.
public
__get(string $name) : Component|null
Parameters
- $name : string
-
Name of component to get.
Return values
Component|null —A Component object or null.
blackHole()
Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error
public
blackHole(Controller $controller[, string $error = '' ][, SecurityException|null $exception = null ]) : mixed
Parameters
- $controller : Controller
-
Instantiating controller
- $error : string = ''
-
Error method
- $exception : SecurityException|null = null
-
Additional debug info describing the cause
Tags
Return values
mixed —If specified, controller blackHoleCallback's response, or no return otherwise
configShallow()
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
public
configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this
Setting a specific value:
$this->configShallow('key', $value);
Setting a nested value:
$this->configShallow('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
Return values
$thisgenerateToken()
Manually add form tampering prevention token information into the provided request object.
public
generateToken(ServerRequest $request) : ServerRequest
Parameters
- $request : ServerRequest
-
The request object to add into.
Return values
ServerRequest —The modified request.
getConfig()
Returns the config.
public
getConfig([string|null $key = null ][, mixed $default = null ]) : mixed
Usage
Reading the whole config:
$this->getConfig();
Reading a specific value:
$this->getConfig('key');
Reading a nested value:
$this->getConfig('some.nested.key');
Reading with default value:
$this->getConfig('some-key', 'default-value');
Parameters
- $key : string|null = null
-
The key to get or null for the whole config.
- $default : mixed = null
-
The return value when the key does not exist.
Return values
mixed —Configuration data at the named key or null if the key does not exist.
getConfigOrFail()
Returns the config for this specific key.
public
getConfigOrFail(string $key) : mixed
The config value for this key must exist, it can never be null.
Parameters
- $key : string
-
The key to get.
Tags
Return values
mixed —Configuration data at the named key
getController()
Get the controller this component is bound to.
public
getController() : Controller
Return values
Controller —The bound controller.
implementedEvents()
Events supported by this component.
public
implementedEvents() : array<string, mixed>
Return values
array<string, mixed>initialize()
Constructor hook method.
public
initialize(array<string, mixed> $config) : void
Implement this method to avoid having to overwrite the constructor and call parent.
Parameters
- $config : array<string, mixed>
-
The configuration settings provided to this component.
log()
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
public
log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
- $message : string
-
Log message.
- $level : string|int = LogLevel::ERROR
-
Error level.
- $context : array<string|int, mixed>|string = []
-
Additional log data relevant to this message.
Return values
bool —Success of log write.
requireSecure()
Sets the actions that require a request that is SSL-secured, or empty for all actions
public
requireSecure([array<string|int, string>|string|null $actions = null ]) : void
Parameters
- $actions : array<string|int, string>|string|null = null
-
Actions list
setConfig()
Sets the config.
public
setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this
Usage
Setting a specific value:
$this->setConfig('key', $value);
Setting a nested value:
$this->setConfig('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
- $merge : bool = true
-
Whether to recursively merge or overwrite existing config, defaults to true.
Tags
Return values
$thisstartup()
Component startup. All security checking happens here.
public
startup(EventInterface $event) : Response|null
Parameters
- $event : EventInterface
-
An Event instance
Return values
Response|null_callback()
Calls a controller callback method
protected
_callback(Controller $controller, string $method[, array<string|int, mixed> $params = [] ]) : mixed
Parameters
- $controller : Controller
-
Instantiating controller
- $method : string
-
Method to execute
- $params : array<string|int, mixed> = []
-
Parameters to send to method
Tags
Return values
mixed —Controller callback method's response
_configDelete()
Deletes a single config key.
protected
_configDelete(string $key) : void
Parameters
- $key : string
-
Key to delete.
Tags
_configRead()
Reads a config key.
protected
_configRead(string|null $key) : mixed
Parameters
- $key : string|null
-
Key to read.
_configWrite()
Writes a config key.
protected
_configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
- $key : array<string, mixed>|string
-
Key to write to.
- $value : mixed
-
Value to write.
- $merge : string|bool = false
-
True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
Tags
_debugCheckFields()
Iterates data array to check against expected
protected
_debugCheckFields(array<string|int, mixed> $dataFields[, array<string|int, mixed> $expectedFields = [] ][, string $intKeyMessage = '' ][, string $stringKeyMessage = '' ][, string $missingMessage = '' ]) : array<string|int, string>
Parameters
- $dataFields : array<string|int, mixed>
-
Fields array, containing the POST data fields
- $expectedFields : array<string|int, mixed> = []
-
Fields array, containing the expected fields we should have in POST
- $intKeyMessage : string = ''
-
Message string if unexpected found in data fields indexed by int (not protected)
- $stringKeyMessage : string = ''
-
Message string if tampered found in data fields indexed by string (protected).
- $missingMessage : string = ''
-
Message string if missing field
Return values
array<string|int, string> —Messages
_debugExpectedFields()
Generate debug message for the expected fields
protected
_debugExpectedFields([array<string|int, mixed> $expectedFields = [] ][, string $missingMessage = '' ]) : string|null
Parameters
- $expectedFields : array<string|int, mixed> = []
-
Expected fields
- $missingMessage : string = ''
-
Message template
Return values
string|null —Error message about expected fields
_debugPostTokenNotMatching()
Create a message for humans to understand why Security token is not matching
protected
_debugPostTokenNotMatching(Controller $controller, array<string|int, string> $hashParts) : string
Parameters
- $controller : Controller
-
Instantiating controller
- $hashParts : array<string|int, string>
-
Elements used to generate the Token hash
Return values
string —Message explaining why the tokens are not matching
_fieldsList()
Return the fields list for the hash calculation
protected
_fieldsList(array<string|int, mixed> $check) : array<string|int, mixed>
Parameters
- $check : array<string|int, mixed>
-
Data array
Return values
array<string|int, mixed>_hashParts()
Return hash parts for the Token generation
protected
_hashParts(Controller $controller) : array<string|int, string>
Parameters
- $controller : Controller
-
Instantiating controller
Return values
array<string|int, string>_matchExistingFields()
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
protected
_matchExistingFields(array<string|int, mixed> $dataFields, array<string|int, mixed> &$expectedFields, string $intKeyMessage, string $stringKeyMessage) : array<string|int, string>
Parameters
- $dataFields : array<string|int, mixed>
-
Fields array, containing the POST data fields
- $expectedFields : array<string|int, mixed>
-
Fields array, containing the expected fields we should have in POST
- $intKeyMessage : string
-
Message string if unexpected found in data fields indexed by int (not protected)
- $stringKeyMessage : string
-
Message string if tampered found in data fields indexed by string (protected)
Return values
array<string|int, string> —Error messages
_secureRequired()
Check if access requires secure connection
protected
_secureRequired(Controller $controller) : void
Parameters
- $controller : Controller
-
Instantiating controller
Tags
_sortedUnlocked()
Get the sorted unlocked string
protected
_sortedUnlocked(array<string|int, mixed> $data) : string
Parameters
- $data : array<string|int, mixed>
-
Data array
Return values
string_throwException()
Check debug status and throw an Exception based on the existing one
protected
_throwException([SecurityException|null $exception = null ]) : void
Parameters
- $exception : SecurityException|null = null
-
Additional debug info describing the cause
Tags
_unlocked()
Get the unlocked string
protected
_unlocked(array<string|int, mixed> $data) : string
Parameters
- $data : array<string|int, mixed>
-
Data array
Return values
string_validatePost()
Validate submitted form
protected
_validatePost(Controller $controller) : void
Parameters
- $controller : Controller
-
Instantiating controller
Tags
_validToken()
Check if token is valid
protected
_validToken(Controller $controller) : string
Parameters
- $controller : Controller
-
Instantiating controller
Tags
Return values
string —fields token