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. .. py:currentmodule:: apifrom.security.headers Overview -------- **Classes** * :py:class:`BaseMiddleware` * :py:class:`CSPDirective` * :py:class:`ContentSecurityPolicy` * :py:class:`ReferrerPolicy` * :py:class:`Request` * :py:class:`Response` * :py:class:`SecurityHeadersMiddleware` * :py:class:`XSSFilter` * :py:class:`XSSProtection` * :py:class:`XSSProtectionMiddleware` Classes ------- .. py:class:: BaseMiddleware(**options):bases: abc.ABC Base middleware class for APIFromAnything. This abstract class defines the interface for middleware components. Middleware components can process requests and responses. .. attribute:: options Options for the middleware. :type: dict Initialize a new BaseMiddleware instance. :param \*\*options: Options for the middleware. .. py:class:: CSPDirective(name) 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') .. :: _nonce :annotation: Optional[str] .. :: name .. :: values :annotation: Set[str] .. method:: _generate_nonce() Generate a random nonce. :returns: A random nonce .. method:: 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 .. method:: allow_none() Disallow content from any source. :returns: The CSP directive instance for method chaining .. method:: allow_self() Allow content from the same origin. :returns: The CSP directive instance for method chaining .. method:: 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 .. method:: allow_strict_dynamic() Allow scripts with the correct nonce to load additional scripts. :returns: The CSP directive instance for method chaining .. method:: allow_unsafe_eval() Allow eval() and similar functions (not recommended for production). :returns: The CSP directive instance for method chaining .. method:: allow_unsafe_inline() Allow inline content (not recommended for production). :returns: The CSP directive instance for method chaining .. method:: get_nonce() Get the nonce for this directive. :returns: The nonce, or None if no nonce has been set .. method:: to_string() Convert the directive to a string. :returns: The directive as a string .. py:class:: ContentSecurityPolicy Content Security Policy builder. This class provides a fluent interface for building Content Security Policies. Initialize the Content Security Policy. .. :: directives :annotation: Dict[str, CSPDirective] .. :: report_only .. :: report_uri .. method:: add_directive(directive) Add a directive to the policy. :param directive: The directive to add :returns: The Content Security Policy instance for method chaining .. method:: base_uri() Get or create the base-uri directive. :returns: The base-uri directive .. method:: connect_src() Get or create the connect-src directive. :returns: The connect-src directive .. method:: create_api_policy() :classmethod: Create a Content Security Policy suitable for APIs. :returns: A Content Security Policy suitable for APIs .. method:: create_strict_policy() :classmethod: Create a strict Content Security Policy. :returns: A strict Content Security Policy .. method:: default_src() Get or create the default-src directive. :returns: The default-src directive .. method:: font_src() Get or create the font-src directive. :returns: The font-src directive .. method:: form_action() Get or create the form-action directive. :returns: The form-action directive .. method:: frame_ancestors() Get or create the frame-ancestors directive. :returns: The frame-ancestors directive .. method:: frame_src() Get or create the frame-src directive. :returns: The frame-src directive .. method:: get_header_name() Get the header name for the policy. :returns: The header name .. method:: img_src() Get or create the img-src directive. :returns: The img-src directive .. method:: manifest_src() Get or create the manifest-src directive. :returns: The manifest-src directive .. method:: media_src() Get or create the media-src directive. :returns: The media-src directive .. method:: object_src() Get or create the object-src directive. :returns: The object-src directive .. method:: script_src() Get or create the script-src directive. :returns: The script-src directive .. method:: 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 .. method:: set_report_uri(uri) Set the report URI. :param uri: The report URI :returns: The Content Security Policy instance for method chaining .. method:: style_src() Get or create the style-src directive. :returns: The style-src directive .. method:: to_string() Convert the policy to a string. :returns: The policy as a string .. method:: worker_src() Get or create the worker-src directive. :returns: The worker-src directive .. py:class:: ReferrerPolicy Referrer Policy values. .. :: NO_REFERRER .. :: NO_REFERRER_WHEN_DOWNGRADE .. :: ORIGIN .. :: ORIGIN_WHEN_CROSS_ORIGIN .. :: SAME_ORIGIN .. :: STRICT_ORIGIN .. :: STRICT_ORIGIN_WHEN_CROSS_ORIGIN .. :: UNSAFE_URL .. py:class:: Request(request = None, path_params = None, method = None, path = None, query_params = None, headers = None, body = None, client_ip = None) Request class for APIFromAnything. This class wraps a Starlette request and provides methods for accessing request data in a convenient way. .. attribute:: _request The underlying Starlette request. .. attribute:: path_params Path parameters extracted from the URL. .. attribute:: query_params Query parameters extracted from the URL. .. attribute:: headers HTTP headers. .. attribute:: method HTTP method. .. attribute:: path Request path. .. attribute:: _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. .. py:class:: Response(content = None, status_code = 200, headers = None, content_type = 'application/json') Response class for APIFromAnything. This class represents an HTTP response and provides methods for setting response data, status code, and headers. .. attribute:: content The response content. .. attribute:: status_code The HTTP status code. .. attribute:: headers HTTP headers. .. attribute:: 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. .. py:class:: 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 .. :: cache_control .. :: content_security_policy .. :: exempt_content_types .. :: exempt_paths .. :: permissions_policy .. :: referrer_policy .. :: strict_transport_security .. :: x_content_type_options .. :: x_frame_options .. :: x_xss_protection .. method:: _add_security_headers(response) Add security headers to a response. :param response: The response to add headers to .. method:: _build_permissions_policy() Build the Permissions-Policy header value. :returns: The Permissions-Policy header value .. method:: _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 .. method:: process_request(request) :async: Process a request through the security headers middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the security headers middleware. :param response: The response to process :returns: The processed response .. py:class:: XSSFilter Filter for preventing Cross-Site Scripting (XSS) attacks. .. method:: escape_html(text) :staticmethod: Escape HTML special characters to prevent XSS attacks. :param text: The text to escape :returns: The escaped text .. method:: 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 .. method:: sanitize_json(data) :staticmethod: Sanitize JSON data to prevent XSS attacks. :param data: The JSON data to sanitize :returns: The sanitized JSON data .. py:class:: XSSProtection X-XSS-Protection values. .. :: DISABLED .. :: ENABLED .. :: ENABLED_BLOCK .. :: ENABLED_REPORT .. py:class:: 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 .. :: allowed_html_attributes .. :: allowed_html_tags .. :: exempt_content_types .. :: exempt_paths .. :: sanitize_html_response .. :: sanitize_json_response .. method:: _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 .. method:: _sanitize_response(response) Sanitize a response to prevent XSS attacks. :param response: The response to sanitize .. method:: process_request(request) :async: Process a request through the XSS protection middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the XSS protection middleware. :param response: The response to process :returns: The processed response