apifrom.security.headersο
Security headers for APIFromAnything.
This module provides middleware and utilities for adding security headers to API responses, including Content Security Policy (CSP), X-XSS-Protection, and other security headers to protect against various web vulnerabilities.
Overviewο
Classes
BaseMiddlewareSecurityHeadersMiddlewareXSSProtectionMiddleware
Classesο
- BaseMiddleware(**options):bases: abc.ABC
Base middleware class for APIFromAnything.
Content Security Policy directive builder.
This class provides a fluent interface for building CSP directives.
Initialize the CSP directive.
- param name:
The name of the directive (e.g., βdefault-srcβ, βscript-srcβ)
- apifrom.security.headers._generate_nonce()ο
Generate a random nonce.
- returns:
A random nonce
- apifrom.security.headers.allow_nonce(nonce=None)ο
Allow content with a specific nonce.
- param nonce:
The nonce to allow (if None, a random nonce will be generated)
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_none()ο
Disallow content from any source.
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_self()ο
Allow content from the same origin.
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_sources(*sources)ο
Allow content from specific sources.
- param *sources:
The sources to allow (e.g., βhttps://example.comβ, β*.example.comβ)
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_strict_dynamic()ο
Allow scripts with the correct nonce to load additional scripts.
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_unsafe_eval()ο
Allow eval() and similar functions (not recommended for production).
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.allow_unsafe_inline()ο
Allow inline content (not recommended for production).
- returns:
The CSP directive instance for method chaining
- apifrom.security.headers.get_nonce()ο
Get the nonce for this directive.
- returns:
The nonce, or None if no nonce has been set
- apifrom.security.headers.to_string()ο
Convert the directive to a string.
- returns:
The directive as a string
Content Security Policy builder.
This class provides a fluent interface for building Content Security Policies.
Initialize the Content Security Policy.
- apifrom.security.headers.add_directive(directive)ο
Add a directive to the policy.
- param directive:
The directive to add
- returns:
The Content Security Policy instance for method chaining
- apifrom.security.headers.base_uri()ο
Get or create the base-uri directive.
- returns:
The base-uri directive
- apifrom.security.headers.connect_src()ο
Get or create the connect-src directive.
- returns:
The connect-src directive
- apifrom.security.headers.create_api_policy()ο
- :classmethod:
Create a Content Security Policy suitable for APIs.
- returns:
A Content Security Policy suitable for APIs
- apifrom.security.headers.create_strict_policy()ο
- :classmethod:
Create a strict Content Security Policy.
- returns:
A strict Content Security Policy
- apifrom.security.headers.default_src()ο
Get or create the default-src directive.
- returns:
The default-src directive
- apifrom.security.headers.font_src()ο
Get or create the font-src directive.
- returns:
The font-src directive
- apifrom.security.headers.form_action()ο
Get or create the form-action directive.
- returns:
The form-action directive
- apifrom.security.headers.frame_ancestors()ο
Get or create the frame-ancestors directive.
- returns:
The frame-ancestors directive
- apifrom.security.headers.frame_src()ο
Get or create the frame-src directive.
- returns:
The frame-src directive
- apifrom.security.headers.get_header_name()ο
Get the header name for the policy.
- returns:
The header name
- apifrom.security.headers.img_src()ο
Get or create the img-src directive.
- returns:
The img-src directive
- apifrom.security.headers.manifest_src()ο
Get or create the manifest-src directive.
- returns:
The manifest-src directive
- apifrom.security.headers.media_src()ο
Get or create the media-src directive.
- returns:
The media-src directive
- apifrom.security.headers.object_src()ο
Get or create the object-src directive.
- returns:
The object-src directive
- apifrom.security.headers.script_src()ο
Get or create the script-src directive.
- returns:
The script-src directive
- apifrom.security.headers.set_report_only(report_only=True)ο
Set whether the policy is report-only.
- param report_only:
Whether the policy is report-only
- returns:
The Content Security Policy instance for method chaining
- apifrom.security.headers.set_report_uri(uri)ο
Set the report URI.
- param uri:
The report URI
- returns:
The Content Security Policy instance for method chaining
- apifrom.security.headers.style_src()ο
Get or create the style-src directive.
- returns:
The style-src directive
- apifrom.security.headers.to_string()ο
Convert the policy to a string.
- returns:
The policy as a string
- apifrom.security.headers.worker_src()ο
Get or create the worker-src directive.
- returns:
The worker-src directive
Referrer Policy values.
- class apifrom.security.headers.Request(request=None, path_params=None, method=None, path=None, query_params=None, headers=None, body=None, client_ip=None)[source]ο
Request class for APIFromAnything.
This class wraps a Starlette request and provides methods for accessing request data in a convenient way.
- apifrom.security.headers._requestο
The underlying Starlette request.
- apifrom.security.headers.path_paramsο
Path parameters extracted from the URL.
- apifrom.security.headers.query_paramsο
Query parameters extracted from the URL.
- apifrom.security.headers.headersο
HTTP headers.
- apifrom.security.headers.methodο
HTTP method.
- apifrom.security.headers.pathο
Request path.
- apifrom.security.headers._bodyο
Cached request body.
Initialize a new Request instance.
- param request:
The underlying Starlette request.
- param path_params:
Path parameters extracted from the URL.
- param method:
The HTTP method.
- param path:
The request path.
- param query_params:
Query parameters.
- param headers:
HTTP headers.
- param body:
Request body.
- param client_ip:
Client IP address.
- class apifrom.security.headers.Response(content=None, status_code=200, headers=None, content_type='application/json')[source]ο
Response class for APIFromAnything.
This class represents an HTTP response and provides methods for setting response data, status code, and headers.
- apifrom.security.headers.contentο
The response content.
- apifrom.security.headers.status_codeο
The HTTP status code.
- apifrom.security.headers.headersο
HTTP headers.
- apifrom.security.headers.content_typeο
The content type of the response.
Initialize a new Response instance.
- param content:
The response content.
- param status_code:
The HTTP status code.
- param headers:
HTTP headers.
- param content_type:
The content type of the response.
- SecurityHeadersMiddleware(content_security_policy = None, x_frame_options = 'DENY', x_content_type_options = 'nosniff', referrer_policy = ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN, x_xss_protection = XSSProtection.ENABLED_BLOCK, strict_transport_security = 'max-age=31536000; includeSubDomains', permissions_policy = None, cache_control = None, exempt_paths = None, exempt_content_types = None):bases: apifrom.middleware.base.BaseMiddleware
Middleware for adding security headers to responses.
Initialize the security headers middleware.
- param content_security_policy:
The Content Security Policy to use
- param x_frame_options:
The X-Frame-Options header value
- param x_content_type_options:
The X-Content-Type-Options header value
- param referrer_policy:
The Referrer-Policy header value
- param x_xss_protection:
The X-XSS-Protection header value
- param strict_transport_security:
The Strict-Transport-Security header value
- param permissions_policy:
The Permissions-Policy header value
- param cache_control:
The Cache-Control header value
- param exempt_paths:
Paths exempt from security headers
- param exempt_content_types:
Content types exempt from security headers
- apifrom.security.headers._add_security_headers(response)ο
Add security headers to a response.
- param response:
The response to add headers to
- apifrom.security.headers._build_permissions_policy()ο
Build the Permissions-Policy header value.
- returns:
The Permissions-Policy header value
- apifrom.security.headers._is_exempt(request, response)ο
Check if a request/response is exempt from security headers.
- param request:
The request
- param response:
The response
- returns:
True if the request/response is exempt, False otherwise
- apifrom.security.headers.process_request(request)ο
- :async:
Process a request through the security headers middleware.
- param request:
The request to process
- returns:
The processed request
- apifrom.security.headers.process_response(response)ο
- :async:
Process a response through the security headers middleware.
- param response:
The response to process
- returns:
The processed response
Filter for preventing Cross-Site Scripting (XSS) attacks.
- apifrom.security.headers.escape_html(text)ο
- :staticmethod:
Escape HTML special characters to prevent XSS attacks.
- param text:
The text to escape
- returns:
The escaped text
- apifrom.security.headers.sanitize_html(html, allowed_tags=None, allowed_attributes=None)ο
- :staticmethod:
Sanitize HTML to prevent XSS attacks.
- param html:
The HTML to sanitize
- param allowed_tags:
The allowed HTML tags
- param allowed_attributes:
The allowed HTML attributes for each tag
- returns:
The sanitized HTML
- apifrom.security.headers.sanitize_json(data)ο
- :staticmethod:
Sanitize JSON data to prevent XSS attacks.
- param data:
The JSON data to sanitize
- returns:
The sanitized JSON data
X-XSS-Protection values.
- XSSProtectionMiddleware(sanitize_json_response = True, sanitize_html_response = False, allowed_html_tags = None, allowed_html_attributes = None, exempt_paths = None, exempt_content_types = None):bases: apifrom.middleware.base.BaseMiddleware
Middleware for preventing Cross-Site Scripting (XSS) attacks.
Initialize the XSS protection middleware.
- param sanitize_json_response:
Whether to sanitize JSON responses
- param sanitize_html_response:
Whether to sanitize HTML responses
- param allowed_html_tags:
The allowed HTML tags for sanitization
- param allowed_html_attributes:
The allowed HTML attributes for sanitization
- param exempt_paths:
Paths exempt from XSS protection
- param exempt_content_types:
Content types exempt from XSS protection
- apifrom.security.headers._is_exempt(request, response)ο
Check if a request/response is exempt from XSS protection.
- param request:
The request
- param response:
The response
- returns:
True if the request/response is exempt, False otherwise
- apifrom.security.headers._sanitize_response(response)ο
Sanitize a response to prevent XSS attacks.
- param response:
The response to sanitize
- apifrom.security.headers.process_request(request)ο
- :async:
Process a request through the XSS protection middleware.
- param request:
The request to process
- returns:
The processed request
- apifrom.security.headers.process_response(response)ο
- :async:
Process a response through the XSS protection middleware.
- param response:
The response to process
- returns:
The processed response