apifrom.security ================ Security module for APIFromAnything. This module provides security features for APIFromAnything, including authentication, authorization, CSRF protection, security headers, and more. .. py:currentmodule:: apifrom.security Overview -------- **Classes** * :py:class:`CSPBuilder` * :py:class:`CSPDirective` * :py:class:`CSPMiddleware` * :py:class:`CSPNonce` * :py:class:`CSPPolicy` * :py:class:`CSPSource` * :py:class:`CSPViolationReporter` * :py:class:`CSRFMiddleware` * :py:class:`CSRFToken` * :py:class:`HSTSMiddleware` * :py:class:`HSTSPreloadChecker` * :py:class:`PermissionsAllowlist` * :py:class:`PermissionsDirective` * :py:class:`PermissionsPolicy` * :py:class:`PermissionsPolicyBuilder` * :py:class:`PermissionsPolicyMiddleware` * :py:class:`SRIBuilder` * :py:class:`SRIGenerator` * :py:class:`SRIHashAlgorithm` * :py:class:`SRIMiddleware` * :py:class:`SRIPolicy` * :py:class:`SecurityHeadersMiddleware` * :py:class:`TrustedTypesBuilder` * :py:class:`TrustedTypesMiddleware` * :py:class:`TrustedTypesPolicy` * :py:class:`TrustedTypesViolationReporter` * :py:class:`XSSProtectionMiddleware` **Functions** * :py:func:`api_key_required` * :py:func:`basic_auth_required` * :py:func:`jwt_required` * :py:func:`oauth2_required` Classes ------- .. py:class:: CSPBuilder Helper class for building CSP policies. .. method:: create_api_policy() :staticmethod: Create a CSP policy suitable for APIs. :returns: A CSP policy for APIs .. method:: create_report_only_policy(report_uri) :staticmethod: Create a report-only CSP policy. :param report_uri: The URI to send violation reports to :returns: A report-only CSP policy .. method:: create_strict_policy() :staticmethod: Create a strict CSP policy. :returns: A strict CSP policy .. method:: create_web_policy() :staticmethod: Create a CSP policy suitable for web applications. :returns: A CSP policy for web applications .. py:class:: CSPDirective Content Security Policy directive constants. .. :: BASE_URI .. :: BLOCK_ALL_MIXED_CONTENT .. :: CONNECT_SRC .. :: DEFAULT_SRC .. :: FONT_SRC .. :: FORM_ACTION .. :: FRAME_ANCESTORS .. :: FRAME_SRC .. :: IMG_SRC .. :: MANIFEST_SRC .. :: MEDIA_SRC .. :: NAVIGATE_TO .. :: OBJECT_SRC .. :: PREFETCH_SRC .. :: REPORT_TO .. :: REPORT_URI .. :: REQUIRE_TRUSTED_TYPES_FOR .. :: SANDBOX .. :: SCRIPT_SRC .. :: STYLE_SRC .. :: TRUSTED_TYPES .. :: UPGRADE_INSECURE_REQUESTS .. :: WORKER_SRC .. py:class:: CSPMiddleware(policy = None, exempt_paths = None, exempt_path_regex = None):bases: apifrom.middleware.base.BaseMiddleware Middleware for adding Content Security Policy headers to responses. Initialize the CSP middleware. :param policy: The CSP policy to apply :param exempt_paths: List of paths to exempt from CSP :param exempt_path_regex: Regex pattern for paths to exempt from CSP .. :: exempt_path_pattern .. :: exempt_path_regex .. :: exempt_paths .. :: policy .. method:: _create_default_policy() Create a default CSP policy. :returns: A default CSP policy .. method:: _is_path_exempt(path) Check if a path is exempt from CSP. :param path: The request path :returns: True if the path is exempt, False otherwise .. method:: process_request(request) :async: Process the request. :param request: The request object :returns: The processed request .. method:: process_response(response) :async: Process the response and add CSP headers. :param response: The response object :returns: The response with CSP headers .. py:class:: CSPNonce Content Security Policy nonce generator. .. method:: generate() :staticmethod: Generate a random nonce for CSP. :returns: A random nonce string .. py:class:: CSPPolicy(report_only = False) Content Security Policy builder. Initialize the CSP policy. :param report_only: Whether to use the report-only mode .. :: directives :annotation: Dict[str, Set[str]] .. :: report_only .. :: reporter :annotation: Optional[CSPViolationReporter] .. method:: add_base_uri(source) Add base-uri directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_block_all_mixed_content() Add block-all-mixed-content directive. :returns: The CSP policy instance for chaining .. method:: add_connect_src(source) Add connect-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_default_src(source) Add default-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_directive(directive, source) Add a directive to the policy. :param directive: The directive name :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_font_src(source) Add font-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_form_action(source) Add form-action directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_frame_ancestors(source) Add frame-ancestors directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_frame_src(source) Add frame-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_img_src(source) Add img-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_manifest_src(source) Add manifest-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_media_src(source) Add media-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_navigate_to(source) Add navigate-to directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_object_src(source) Add object-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_prefetch_src(source) Add prefetch-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_require_trusted_types_for(value = 'script') Add require-trusted-types-for directive. :param value: The value for the directive :returns: The CSP policy instance for chaining .. method:: add_sandbox(value) Add sandbox directive. :param value: The sandbox value(s) :returns: The CSP policy instance for chaining .. method:: add_script_src(source) Add script-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_style_src(source) Add style-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: add_trusted_types(value) Add trusted-types directive. :param value: The trusted types value(s) :returns: The CSP policy instance for chaining .. method:: add_upgrade_insecure_requests() Add upgrade-insecure-requests directive. :returns: The CSP policy instance for chaining .. method:: add_worker_src(source) Add worker-src directive. :param source: The source value(s) :returns: The CSP policy instance for chaining .. method:: get_header_name() Get the appropriate header name based on the policy mode. :returns: The CSP header name .. method:: set_reporter(reporter) Set the violation reporter. :param reporter: The violation reporter :returns: The CSP policy instance for chaining .. method:: to_header() Convert the policy to a header value. :returns: The CSP header value .. method:: to_header_value() Convert the policy to a header value. This is an alias for to_header() for backward compatibility. :returns: The CSP header value .. py:class:: CSPSource Content Security Policy source constants. .. :: BLOB .. :: DATA .. :: FILESYSTEM .. :: HTTPS .. :: MEDIASTREAM .. :: NONE .. :: REPORT_SAMPLE .. :: SELF .. :: STRICT_DYNAMIC .. :: UNSAFE_EVAL .. :: UNSAFE_HASHES .. :: UNSAFE_INLINE .. :: WS .. :: WSS .. py:class:: CSPViolationReporter(report_uri = None, report_to = None, callback = None) Content Security Policy violation reporter. Initialize the CSP violation reporter. :param report_uri: The URI to send violation reports to :param report_to: The reporting group to send violation reports to :param callback: A callback function to handle violation reports .. :: callback .. :: report_to .. :: report_uri .. method:: get_directives() Get the reporting directives. :returns: A dictionary of reporting directives .. method:: handle_report(report) :async: Handle a CSP violation report. :param report: The violation report .. py:class:: CSRFMiddleware(secret = None, token_name = 'csrf_token', header_name = 'X-CSRF-Token', cookie_name = 'csrf_token', cookie_path = '/', cookie_secure = True, cookie_http_only = True, cookie_same_site = 'Lax', exempt_methods = None, exempt_routes = None, error_message = 'CSRF token validation failed'):bases: apifrom.middleware.base.BaseMiddleware Middleware for CSRF protection. Initialize the CSRF middleware. :param secret: Secret key for token generation (defaults to a random key) :param token_name: Name of the token in forms and query parameters :param header_name: Name of the token header :param cookie_name: Name of the token cookie :param cookie_path: Path for the token cookie :param cookie_secure: Whether the cookie should be secure (HTTPS only) :param cookie_http_only: Whether the cookie should be HTTP only :param cookie_same_site: SameSite attribute for the cookie :param exempt_methods: HTTP methods exempt from CSRF protection :param exempt_routes: Routes exempt from CSRF protection :param error_message: Error message for CSRF validation failures .. :: cookie_http_only .. :: cookie_name .. :: cookie_path .. :: cookie_same_site .. :: cookie_secure .. :: error_message .. :: exempt_methods .. :: exempt_routes .. :: header_name .. :: secret .. :: token_name .. method:: _generate_token(session_id = None) Generate a new CSRF token. :param session_id: The session ID to use for token generation :returns: The generated token .. method:: _get_session_id(request) Get the session ID from a request. :param request: The request to get the session ID from :returns: The session ID, or None if not found .. method:: _get_token_from_request(request) Get the CSRF token from a request. :param request: The request to get the token from :returns: The CSRF token, or None if not found .. method:: _is_exempt(request) Check if a request is exempt from CSRF protection. :param request: The request to check :returns: True if the request is exempt, False otherwise .. method:: _set_csrf_cookie(response, token) Set the CSRF token cookie on a response. :param response: The response to set the cookie on :param token: The CSRF token .. method:: _validate_token(token, session_id = None) Validate a CSRF token. :param token: The token to validate :param session_id: The session ID to validate against :returns: True if the token is valid, False otherwise .. method:: process_request(request) :async: Process a request through the CSRF middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the CSRF middleware. :param response: The response to process :returns: The processed response .. py:class:: CSRFToken(secret = None, token_length = 32, max_age = 3600) CSRF token generator and validator. Initialize the CSRF token generator. :param secret: Secret key for token generation (defaults to a random key) :param token_length: Length of the token in bytes :param max_age: Maximum age of tokens in seconds .. :: max_age .. :: secret .. :: token_length .. method:: _create_signature(data) Create a signature for the given data. :param data: The data to sign :returns: The signature .. method:: generate_token(session_id = None) Generate a new CSRF token. :param session_id: Session ID to bind the token to (optional) :returns: A new CSRF token .. method:: validate_token(token, session_id = None) Validate a CSRF token. :param token: The token to validate :param session_id: Session ID to validate against (optional) :returns: True if the token is valid, False otherwise .. py:class:: HSTSMiddleware(max_age = 31536000, include_subdomains = True, preload = False, force_https_redirect = True, exempt_paths = None):bases: apifrom.middleware.base.BaseMiddleware Middleware for implementing HTTP Strict Transport Security (HSTS). This middleware adds the Strict-Transport-Security header to responses to instruct browsers to only use HTTPS for your API. Initialize the HSTS middleware. :param max_age: The time, in seconds, that the browser should remember that a site is only to be accessed using HTTPS :param include_subdomains: Whether the HSTS policy applies to all subdomains :param preload: Whether to include the site in the HSTS preload list :param force_https_redirect: Whether to redirect HTTP requests to HTTPS :param exempt_paths: Paths exempt from HSTS .. :: exempt_paths .. :: force_https_redirect .. :: include_subdomains .. :: max_age .. :: preload .. method:: _add_hsts_header(response) Add the Strict-Transport-Security header to a response. :param response: The response to add the header to .. method:: _build_hsts_header() Build the Strict-Transport-Security header value. :returns: The header value .. method:: _get_https_redirect_url(request) Get the HTTPS redirect URL for a request. :param request: The request to redirect :returns: The HTTPS redirect URL .. method:: _is_exempt(request) Check if a request is exempt from HSTS. :param request: The request to check :returns: True if the request is exempt, False otherwise .. method:: _is_https(request) Check if a request is using HTTPS. :param request: The request to check :returns: True if the request is using HTTPS, False otherwise .. method:: process_request(request) :async: Process a request through the HSTS middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the HSTS middleware. :param response: The response to process :returns: The processed response .. py:class:: HSTSPreloadChecker Utility for checking if a domain is eligible for HSTS preloading. This class provides methods to check if a domain meets the requirements for inclusion in the HSTS preload list. .. method:: check_eligibility(domain, hsts_header, has_valid_certificate = True, all_subdomains_https = False, redirect_to_https = True) :staticmethod: Check if a domain is eligible for HSTS preloading. :param domain: The domain to check :param hsts_header: The Strict-Transport-Security header value :param has_valid_certificate: Whether the domain has a valid SSL/TLS certificate :param all_subdomains_https: Whether all subdomains support HTTPS :param redirect_to_https: Whether the domain redirects HTTP to HTTPS :returns: A dictionary with the eligibility status and any issues .. method:: get_submission_instructions(domain) :staticmethod: Get instructions for submitting a domain to the HSTS preload list. :param domain: The domain to submit :returns: Instructions for submitting the domain .. py:class:: PermissionsAllowlist Allowlist values for Permissions Policy directives. .. :: ANY .. :: NONE .. :: SELF .. :: SRC .. py:class:: PermissionsDirective Permissions Policy directive constants. .. :: ACCELEROMETER .. :: ALL .. :: AMBIENT_LIGHT_SENSOR .. :: AUTOPLAY .. :: CAMERA .. :: CLIPBOARD_READ .. :: CLIPBOARD_WRITE .. :: CROSS_ORIGIN_ISOLATED .. :: DISPLAY_CAPTURE .. :: DOCUMENT_DOMAIN .. :: ENCRYPTED_MEDIA .. :: EXECUTION_WHILE_NOT_RENDERED .. :: EXECUTION_WHILE_OUT_OF_VIEWPORT .. :: FOCUS_WITHOUT_USER_ACTIVATION .. :: FORMS .. :: FULLSCREEN .. :: GEOLOCATION .. :: GYROSCOPE .. :: HOVERED_OVER_BROWSING_CONTEXT .. :: IDLE_DETECTION .. :: MAGNETOMETER .. :: MICROPHONE .. :: MIDI .. :: NAVIGATION_OVERRIDE .. :: PAYMENT .. :: PICTURE_IN_PICTURE .. :: POPUP .. :: SCREEN_WAKE_LOCK .. :: SPEAKER_SELECTION .. :: SYNC_XHR .. :: USB .. :: VERTICAL_SCROLL .. :: WEB_SHARE .. :: XR_SPATIAL_TRACKING .. py:class:: PermissionsPolicy Policy for configuring Permissions Policy. This class represents a Permissions Policy that can be used to control which browser features and APIs are available to a document and its embedded frames. Initialize the Permissions Policy. .. :: directives :annotation: Dict[str, Set[str]] .. method:: _add_allowlist_value(directive, value) Add an allowlist value to a directive. :param directive: The directive name :param value: The allowlist value .. method:: add_directive(directive, allowlist) Add a directive to the policy. :param directive: The directive name :param allowlist: The allowlist value(s) :returns: The policy instance for chaining .. method:: disable_all() Disable all features for all origins. :returns: The policy instance for chaining .. method:: enable_for_self(directives) Enable specified features for the same origin. :param directives: The directives to enable :returns: The policy instance for chaining .. method:: to_header() Convert the policy to a header value. :returns: The Permissions-Policy header value .. method:: to_header_value() Convert the policy to a header value. This is an alias for to_header() for backward compatibility. :returns: The Permissions-Policy header value .. py:class:: PermissionsPolicyBuilder Helper class for building Permissions Policy. .. method:: create_api_policy() :staticmethod: Create a Permissions Policy suitable for APIs. :returns: A Permissions Policy for APIs .. method:: create_minimal_policy() :staticmethod: Create a minimal Permissions Policy that disables sensitive features. :returns: A minimal Permissions Policy .. method:: create_strict_policy() :staticmethod: Create a strict Permissions Policy that disables all features. :returns: A strict Permissions Policy .. method:: create_web_policy() :staticmethod: Create a Permissions Policy suitable for web applications. :returns: A Permissions Policy for web applications .. py:class:: PermissionsPolicyMiddleware(policy = None, exempt_paths = None):bases: apifrom.middleware.base.BaseMiddleware Middleware for adding Permissions Policy headers to responses. This middleware adds the Permissions-Policy header to responses to control which browser features and APIs are available to a document and its embedded frames. Initialize the Permissions Policy middleware. :param policy: The Permissions Policy to apply :param exempt_paths: Paths exempt from Permissions Policy .. :: exempt_paths .. :: policy .. method:: _create_default_policy() Create a default Permissions Policy. :returns: A default Permissions Policy .. method:: _is_exempt(request) Check if a request is exempt from Permissions Policy. :param request: The request to check :returns: True if the request is exempt, False otherwise .. method:: process_request(request) :async: Process a request through the Permissions Policy middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the Permissions Policy middleware. :param response: The response to process :returns: The processed response .. py:class:: SRIBuilder Helper class for building SRI policies. .. method:: create_common_cdn_policy() :staticmethod: Create an SRI policy for common CDN resources. :returns: An SRI policy for common CDN resources .. method:: create_empty_policy() :staticmethod: Create an empty SRI policy. :returns: An empty SRI policy .. method:: create_policy_from_html(html_content) :staticmethod: :async: Create an SRI policy from HTML content by extracting script and link tags. :param html_content: The HTML content to extract sources from :returns: An SRI policy with the extracted sources .. py:class:: SRIGenerator Utility for generating Subresource Integrity hashes. .. method:: generate_hash(content, algorithm = SRIHashAlgorithm.SHA384) :staticmethod: Generate a Subresource Integrity hash for the given content. :param content: The content to hash (string or bytes) :param algorithm: The hash algorithm to use :returns: The SRI hash string in the format 'algorithm-base64hash' .. method:: generate_integrity_attribute(content, algorithms = None) :staticmethod: Generate a complete integrity attribute for HTML elements. :param content: The content to hash :param algorithms: The hash algorithms to use (defaults to [SHA384]) :returns: The integrity attribute value with multiple hashes if requested .. method:: verify_integrity(content, integrity_value) :staticmethod: Verify that content matches an integrity value. :param content: The content to verify :param integrity_value: The integrity value to check against :returns: True if the content matches any of the hashes in the integrity value .. py:class:: SRIHashAlgorithm:bases: enum.Enum Hash algorithms supported by Subresource Integrity. .. :: SHA256 .. :: SHA384 .. :: SHA512 .. py:class:: SRIMiddleware(script_sources = None, style_sources = None, verify_external_resources = False, algorithms = None, exempt_paths = None):bases: apifrom.middleware.base.BaseMiddleware Middleware for adding Subresource Integrity headers to responses. This middleware can modify HTML responses to add integrity attributes to script and link tags that load external resources. :param script_sources: Dictionary mapping script URLs to their integrity values :param style_sources: Dictionary mapping style URLs to their integrity values :param verify_external_resources: Whether to verify external resources :param algorithms: List of hash algorithms to use for verification :param exempt_paths: Paths exempt from SRI .. :: _integrity_cache :annotation: Dict[str, str] .. :: algorithms .. :: exempt_paths .. :: script_sources .. :: style_sources .. :: verify_external_resources .. method:: _add_integrity_to_html(html_content) Add integrity attributes to script and link tags in HTML content. :param html_content: The HTML content to modify :returns: The modified HTML content .. method:: _fetch_and_compute_integrity(url) :async: Fetch a resource and compute its integrity value. :param url: The URL of the resource to fetch :returns: The integrity value, or None if the resource could not be fetched .. method:: _is_exempt(request) Check if a request is exempt from SRI processing. :param request: The request to check :returns: True if the request is exempt, False otherwise .. method:: process_request(request) :async: Process a request through the SRI middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the SRI middleware. :param response: The response to process :returns: The processed response .. py:class:: SRIPolicy Policy for configuring Subresource Integrity. Initialize the SRI policy. .. :: algorithms .. :: script_sources .. :: style_sources .. :: verify_external_resources .. method:: _compute_integrity(url) :async: Compute the integrity value for a URL. :param url: The URL to compute the integrity for :returns: The integrity value, or None if it could not be computed .. method:: add_script_source(url, integrity = None) Add a script source to the policy. :param url: The URL of the script :param integrity: The integrity value (will be computed if None) :returns: The SRI policy instance for chaining .. method:: add_style_source(url, integrity = None) Add a style source to the policy. :param url: The URL of the stylesheet :param integrity: The integrity value (will be computed if None) :returns: The SRI policy instance for chaining .. method:: compute_missing_integrity_values() :async: Compute integrity values for sources that don't have them. :returns: The SRI policy instance for chaining .. method:: enable_verification(enable = True) Enable or disable verification of external resources. :param enable: Whether to enable verification :returns: The SRI policy instance for chaining .. method:: set_algorithms(algorithms) Set the hash algorithms to use. :param algorithms: The hash algorithms to use :returns: The SRI policy instance for chaining .. 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:: TrustedTypesBuilder Helper class for building Trusted Types policies. .. method:: create_default_policy() :staticmethod: Create a default Trusted Types policy. :returns: A default Trusted Types policy .. method:: create_escape_policy() :staticmethod: Create a Trusted Types policy that escapes HTML. :returns: A Trusted Types policy that escapes HTML .. method:: create_sanitize_policy() :staticmethod: Create a Trusted Types policy that sanitizes HTML. :returns: A Trusted Types policy that sanitizes HTML .. method:: create_url_policy() :staticmethod: Create a Trusted Types policy for URLs. :returns: A Trusted Types policy for URLs .. py:class:: TrustedTypesMiddleware(policies = None, require_for_script = True, allow_duplicates = False, report_only = False, report_uri = None, exempt_paths = None):bases: apifrom.middleware.base.BaseMiddleware Middleware for adding Trusted Types headers and scripts to responses. This middleware adds the Content-Security-Policy header with the require-trusted-types-for directive to enforce Trusted Types for script execution, and injects a script to create Trusted Types policies. Initialize the Trusted Types middleware. :param policies: List of Trusted Types policies to create :param require_for_script: Whether to require Trusted Types for script execution :param allow_duplicates: Whether to allow duplicate policy names :param report_only: Whether to use report-only mode :param report_uri: URI to report violations to :param exempt_paths: Paths exempt from Trusted Types .. :: allow_duplicates .. :: exempt_paths .. :: policies .. :: report_only .. :: report_uri .. :: require_for_script .. method:: _generate_policy_script() Generate a script to create Trusted Types policies. :returns: A script element with the policy creation code .. method:: _get_csp_header_name() Get the CSP header name based on the mode. :returns: The CSP header name .. method:: _get_csp_header_value() Get the CSP header value for Trusted Types. :returns: The CSP header value .. method:: _inject_policy_script(response) Inject the policy script into HTML content. :param response: The response or HTML content to modify :returns: The modified response or HTML content .. method:: _is_exempt(request) Check if a request is exempt from Trusted Types. :param request: The request to check :returns: True if the request is exempt, False otherwise .. method:: process_request(request) :async: Process a request through the Trusted Types middleware. :param request: The request to process :returns: The processed request .. method:: process_response(response) :async: Process a response through the Trusted Types middleware. :param response: The response to process :returns: The processed response .. py:class:: TrustedTypesPolicy(name, enforce = True) Policy for configuring Trusted Types. This class represents a Trusted Types policy that can be used to create trusted values for various DOM sinks. Initialize the Trusted Types policy. :param name: The name of the policy :param enforce: Whether to enforce the policy .. :: enforce .. :: html_handlers :annotation: List[Callable[[str], str]] .. :: name .. :: script_handlers :annotation: List[Callable[[str], str]] .. :: script_url_handlers :annotation: List[Callable[[str], str]] .. :: url_handlers :annotation: List[Callable[[str], str]] .. method:: add_html_handler(handler) Add an HTML handler. :param handler: The handler function :returns: The policy instance for chaining .. method:: add_script_handler(handler) Add a script handler. :param handler: The handler function :returns: The policy instance for chaining .. method:: add_script_url_handler(handler) Add a script URL handler. :param handler: The handler function :returns: The policy instance for chaining .. method:: add_url_handler(handler) Add a URL handler. :param handler: The handler function :returns: The policy instance for chaining .. method:: create_html(html) Create trusted HTML. :param html: The HTML to create :returns: The trusted HTML .. method:: create_script(script) Create a trusted script. :param script: The script to create :returns: The trusted script .. method:: create_script_url(url) Create a trusted script URL. :param url: The URL to create :returns: The trusted script URL .. method:: create_url(url) Create a trusted URL. :param url: The URL to create :returns: The trusted URL .. method:: to_js() Convert the policy to JavaScript code. :returns: JavaScript code for creating the policy .. py:class:: TrustedTypesViolationReporter(report_uri, callback = None) Reporter for Trusted Types violations. This class provides utilities for handling Trusted Types violation reports. Initialize the Trusted Types violation reporter. :param report_uri: The URI to send violation reports to :param callback: A callback function to handle violation reports .. :: callback .. :: report_uri .. method:: get_report_uri() Get the report URI. :returns: The report URI .. method:: handle_report(report) :async: Handle a Trusted Types violation report. :param report: The violation 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 Functions --------- .. py:function:: api_key_required(func=None, *, api_keys = None, scopes = None, error_message = 'Invalid or missing API key') Decorator to require a valid API key for an API endpoint. :param func: The function to decorate. :param api_keys: A dictionary of API keys and their scopes. If None, uses the API instance's API keys. The values can be strings, lists of strings, or dictionaries with a 'scopes' key. :param scopes: A list of scopes that the API key must have. :param error_message: The error message to return if the API key is invalid. :returns: The decorated function. .. py:function:: basic_auth_required(func=None, *, credentials = None, error_message = 'Invalid or missing credentials') Decorator to require valid Basic auth credentials for an API endpoint. :param func: The function to decorate. :param credentials: A dictionary of username-password pairs. If None, uses the API instance's Basic auth credentials. :param error_message: The error message to return if the credentials are invalid. :returns: The decorated function. .. py:function:: jwt_required(func=None, *, secret = None, algorithm = None, verify_exp = True, verify_aud = False, audience = None, verify_iss = False, issuer = None, verify_sub = False, subject = None, required_claims = None, optional_claims = None, error_message = 'Invalid or missing JWT token') Decorator that requires a valid JWT token for accessing the endpoint. :param secret: The secret key used to decode the JWT token :param algorithm: The algorithm used to decode the JWT token :param verify_exp: Whether to verify the expiration time :param verify_aud: Whether to verify the audience :param audience: The expected audience :param verify_iss: Whether to verify the issuer :param issuer: The expected issuer :param verify_sub: Whether to verify the subject :param subject: The expected subject :param required_claims: List of claims that must be present in the token :param optional_claims: List of claims that may be present in the token :param error_message: The error message to return if the token is invalid :returns: The decorated function .. py:function:: oauth2_required(func=None, *, scopes = None, token_url = None, error_message = 'Invalid or missing OAuth2 token') Decorator to require a valid OAuth2 token for an API endpoint. This is a placeholder implementation. In a real application, you would integrate with an OAuth2 provider like Auth0, Okta, or your own OAuth2 server. :param func: The function to decorate. :param scopes: A list of scopes that the token must have. :param token_url: The URL for obtaining tokens. :param error_message: The error message to return if the token is invalid. :returns: The decorated function.