Content Security Policy
Relevant source files
The following files were used as context for generating this wiki page:
Content Security Policy (CSP) is a security feature in CodeIgniter 4 designed to mitigate common injection attacks, such as Cross-Site Scripting (XSS). It operates by defining a whitelist of trusted sources from which resources like scripts, styles, and images can be loaded by the browser. By specifying a CSP header in the HTTP response, the framework instructs the browser to only execute or render resources from these approved sources, effectively blocking any malicious assets injected from elsewhere.
The CSP functionality is integrated directly into the framework's Response object, allowing for both global and per-response configuration. It can be enabled globally and configured with default policies, which can then be dynamically modified within controllers for specific pages. This provides a flexible and powerful way to enhance application security.
Sources: user_guide_src/source/general/security.rst:11-13, user_guide_src/source/general/security.rst:104-106, user_guide_src/source/outgoing/response.rst:419-421
Enabling and Configuration
CSP is disabled by default. To enable it for your application, you must modify the main application configuration file.
Sources: user_guide_src/source/general/security.rst:108
Global Activation
To activate CSP, set the $CSPEnabled property to true in the app/Config/App.php file. When enabled, the Response class will automatically include the CSP header in all outgoing responses.
// In app/Config/App.php
public bool $CSPEnabled = true;
Sources: user_guide_src/source/installation/running.rst:114-116, user_guide_src/source/general/security.rst:108-110
Default Policy Configuration
The default CSP rules are defined in the app/Config/ContentSecurityPolicy.php configuration file. This file contains properties that map directly to the CSP directives. You can modify this file to set your application-wide security policy.
The following diagram shows the process of enabling and configuring CSP.
This flowchart illustrates the initial setup for Content Security Policy in a CodeIgniter 4 application.
Sources: user_guide_src/source/outgoing/response.rst:423-425
The table below lists the primary configuration properties available in app/Config/ContentSecurityPolicy.php and their default values.
| Property/Directive | Description | Default Value |
|---|---|---|
default-src | The default policy for fetching resources. | 'self' |
script-src | Defines valid sources for JavaScript. | 'self' |
style-src | Defines valid sources for stylesheets. | 'self' |
image-src | Defines valid sources for images. | 'self' |
base-uri | Restricts the URLs which can be used in a document's <base> element. | null |
child-src | Defines valid sources for web workers and nested browsing contexts. | 'self' |
connect-src | Applies to fetch, XMLHttpRequest, WebSocket, etc. | 'self' |
font-src | Specifies valid sources for fonts loaded using @font-face. | null |
form-action | Specifies valid endpoints for submissions from <form> tags. | 'self' |
frame-ancestors | Specifies valid parents that may embed a page using <frame>, <iframe>, etc. | null |
media-src | Specifies valid sources for loading media using <audio> and <video>. | null |
object-src | Specifies valid sources for the <object>, <embed>, and <applet> elements. | null |
plugin-types | Restricts the set of plugins that can be embedded. | null |
report-uri | Specifies a URL where a browser will send reports about policy failures. | null |
sandbox | Applies restrictions to a resource's actions, similar to an <iframe> sandbox. | null |
upgrade-insecure-requests | Instructs user agents to treat all of a site's insecure URLs as if they have been replaced with secure URLs. | false (boolean) |
Sources: user_guide_src/source/outgoing/response.rst:431-482
Dynamic Usage in Controllers
While global policies are set in the configuration file, you can dynamically modify the CSP for a specific response within your controllers. The Response object provides a CSP method that returns an instance of the ContentSecurityPolicy object, allowing you to alter directives on the fly.
Sources: user_guide_src/source/outgoing/response.rst:487-489
Modifying Directives
You can add new sources to any directive using a set of dedicated methods. For example, to allow scripts from https://api.example.com, you would use addScriptSrc().
// In a controller method
public function index()
{
$this->response->CSP()
->addScriptSrc('https://api.example.com');
return view('my_view');
}
This will append the new source to the existing script-src policy for the current response only.
The following sequence diagram shows how a controller modifies the CSP for a response.
This diagram illustrates the sequence of events when a controller dynamically adds a new source to the Content Security Policy.
Sources: user_guide_src/source/outgoing/response.rst:491-499
Using Nonces for Inline Scripts and Styles
A common and secure CSP practice is to disallow all inline scripts and styles. However, sometimes they are necessary. CSP handles this using a "nonce" (number used once), a unique random string that is generated for each request. This nonce is added to the CSP header and must also be present in the <script> or <style> tag for the browser to execute it.
CodeIgniter provides helper functions to automatically manage nonces.
Sources: user_guide_src/source/outgoing/response.rst:512-516, user_guide_src/source/helpers/csp_helper.rst:10-13
CSP Helper
To use nonces, you must first load the CSP helper. Then, you can use the csp_script_nonce() and csp_style_nonce() functions within your view files. These functions will output the correct nonce="..." attribute.
// In your view file
<script <?= csp_script_nonce() ?>>
// Your inline script here...
alert('This script will be allowed by CSP.');
</script>
<style <?= csp_style_nonce() ?>>
/* Your inline styles here... */
body { color: #000; }
</style>
The framework automatically generates the nonce, adds it to the script-src and style-src directives in the Content-Security-Policy header, and the helper functions ensure the matching nonce is placed in the HTML tags.
Sources: user_guide_src/source/helpers/csp_helper.rst:21-34
Report-Only Mode
CSP can be deployed in "report-only" mode. In this mode, the browser does not block any resources that violate the policy. Instead, it sends a JSON report to a specified URI. This is extremely useful for testing a new policy without breaking your site's functionality.
To enable this mode for a response, chain the reportOnly() method.
// In a controller method
public function testPolicy()
{
$this->response->CSP()->reportOnly()->addImgSrc('https://images.example.com');
return view('my_view');
}
This will send the Content-Security-Policy-Report-Only header instead of the enforcing Content-Security-Policy header. The report-uri directive must be set in your configuration for reports to be sent.
Sources: user_guide_src/source/outgoing/response.rst:504-510
Summary
CodeIgniter 4's Content Security Policy feature provides a robust and flexible mechanism for preventing XSS and other injection attacks. By enabling it via a simple configuration flag, developers can establish a baseline security policy. This policy can be fine-tuned globally in a dedicated configuration file or dynamically adjusted on a per-response basis within controllers. Support for nonces via helper functions makes it practical to use strict policies while still allowing necessary inline scripts and styles securely. Finally, the report-only mode allows for safe testing and rollout of new policies.
Sources: user_guide_src/source/general/security.rst:104-110, user_guide_src/source/outgoing/response.rst:419-425, user_guide_src/source/helpers/csp_helper.rst:10-13