public function CspSettingsForm::validateForm in Content-Security-Policy 8
Form validation handler.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Overrides FormBase::validateForm
File
- src/
Form/ CspSettingsForm.php, line 519
Class
- CspSettingsForm
- Form for editing Content Security Policy module settings.
Namespace
Drupal\csp\FormCode
public function validateForm(array &$form, FormStateInterface $form_state) {
foreach ([
'report-only',
'enforce',
] as $policyTypeKey) {
$directiveNames = $this
->getConfigurableDirectives();
foreach ($directiveNames as $directiveName) {
if ($directiveSources = $form_state
->getValue([
$policyTypeKey,
'directives',
$directiveName,
'sources',
])) {
$sourcesArray = preg_split('/,?\\s+/', $directiveSources);
$hasNonceSource = array_reduce($sourcesArray, function ($return, $value) {
return $return || preg_match("<^'nonce->", $value);
}, FALSE);
if ($hasNonceSource) {
$form_state
->setError($form[$policyTypeKey]['directives'][$directiveName]['options']['sources'], $this
->t('<a href=":docUrl">Nonces must be a unique value for each request</a>, so cannot be set in configuration.', [
':docUrl' => 'https://www.w3.org/TR/CSP3/#security-considerations',
]));
}
// '{hashAlgorithm}-{base64-value}'
$hashAlgoMatch = '(' . implode('|', Csp::HASH_ALGORITHMS) . ')-[\\w+/_-]+=*';
$hasInvalidSource = array_reduce($sourcesArray, function ($return, $value) use ($hashAlgoMatch) {
return $return || !(preg_match('<^([a-z]+:)?$>', $value) || static::isValidHost($value) || preg_match("<^'(" . $hashAlgoMatch . ")'\$>", $value));
}, FALSE);
if ($hasInvalidSource) {
$form_state
->setError($form[$policyTypeKey]['directives'][$directiveName]['options']['sources'], $this
->t('Invalid domain or protocol provided.'));
}
}
}
// Don't validate if not enabled; value will be skipped on save.
if ($form_state
->getValue([
$policyTypeKey,
'directives',
'plugin-types',
'enable',
])) {
$invalidTypes = array_reduce(preg_split('/,?\\s+/', $form_state
->getValue([
$policyTypeKey,
'directives',
'plugin-types',
'mime-types',
], '')), function ($return, $value) {
return $return || !preg_match('<^([\\w-]+/[\\w-]+)?$>', $value);
}, FALSE);
if ($invalidTypes) {
$form_state
->setError($form[$policyTypeKey]['directives']['plugin-types']['options']['mime-types'], $this
->t('Invalid MIME-Type provided.'));
}
}
if ($reportingHandlerPluginId = $form_state
->getValue([
$policyTypeKey,
'reporting',
'handler',
])) {
$form[$policyTypeKey]['reporting'][$reportingHandlerPluginId]['#CspReportingHandlerPlugin']
->validateForm($form[$policyTypeKey]['reporting'][$reportingHandlerPluginId], $form_state);
}
else {
$form_state
->setError($form[$policyTypeKey]['reporting']['handler'], $this
->t('Reporting Handler is required for enabled policies.'));
}
}
parent::validateForm($form, $form_state);
}