apifrom.security

Security module for APIFromAnything.

This module provides security features for APIFromAnything, including authentication, authorization, CSRF protection, security headers, and more.

Overview

Classes

Functions

Classes

class apifrom.security.CSPBuilder[source]

Helper class for building CSP policies.

apifrom.security.create_api_policy()
:staticmethod:

Create a CSP policy suitable for APIs.

returns:

A CSP policy for APIs

apifrom.security.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

apifrom.security.create_strict_policy()
:staticmethod:

Create a strict CSP policy.

returns:

A strict CSP policy

apifrom.security.create_web_policy()
:staticmethod:

Create a CSP policy suitable for web applications.

returns:

A CSP policy for web applications

class apifrom.security.CSPDirective[source]

Content Security Policy directive constants.

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

apifrom.security._create_default_policy()

Create a default CSP policy.

returns:

A default CSP policy

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process the request.

param request:

The request object

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process the response and add CSP headers.

param response:

The response object

returns:

The response with CSP headers

class apifrom.security.CSPNonce[source]

Content Security Policy nonce generator.

apifrom.security.generate()
:staticmethod:

Generate a random nonce for CSP.

returns:

A random nonce string

class apifrom.security.CSPPolicy(report_only=False)[source]
Parameters:

report_only (bool)

Content Security Policy builder.

Initialize the CSP policy.

param report_only:

Whether to use the report-only mode

apifrom.security.add_base_uri(source)

Add base-uri directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_block_all_mixed_content()

Add block-all-mixed-content directive.

returns:

The CSP policy instance for chaining

apifrom.security.add_connect_src(source)

Add connect-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_default_src(source)

Add default-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.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

apifrom.security.add_font_src(source)

Add font-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_form_action(source)

Add form-action directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_frame_ancestors(source)

Add frame-ancestors directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_frame_src(source)

Add frame-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_img_src(source)

Add img-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_manifest_src(source)

Add manifest-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_media_src(source)

Add media-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_navigate_to(source)

Add navigate-to directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_object_src(source)

Add object-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_prefetch_src(source)

Add prefetch-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.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

apifrom.security.add_sandbox(value)

Add sandbox directive.

param value:

The sandbox value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_script_src(source)

Add script-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_style_src(source)

Add style-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_trusted_types(value)

Add trusted-types directive.

param value:

The trusted types value(s)

returns:

The CSP policy instance for chaining

apifrom.security.add_upgrade_insecure_requests()

Add upgrade-insecure-requests directive.

returns:

The CSP policy instance for chaining

apifrom.security.add_worker_src(source)

Add worker-src directive.

param source:

The source value(s)

returns:

The CSP policy instance for chaining

apifrom.security.get_header_name()

Get the appropriate header name based on the policy mode.

returns:

The CSP header name

apifrom.security.set_reporter(reporter)

Set the violation reporter.

param reporter:

The violation reporter

returns:

The CSP policy instance for chaining

apifrom.security.to_header()

Convert the policy to a header value.

returns:

The CSP header value

apifrom.security.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

class apifrom.security.CSPSource[source]

Content Security Policy source constants.

class apifrom.security.CSPViolationReporter(report_uri=None, report_to=None, callback=None)[source]
Parameters:
  • report_uri (Optional[str])

  • report_to (Optional[str])

  • callback (Optional[Callable[[Dict[str, Any]], 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

apifrom.security.get_directives()

Get the reporting directives.

returns:

A dictionary of reporting directives

apifrom.security.handle_report(report)
:async:

Handle a CSP violation report.

param report:

The violation report

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

apifrom.security._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

apifrom.security._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

apifrom.security._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

apifrom.security._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

Set the CSRF token cookie on a response.

param response:

The response to set the cookie on

param token:

The CSRF token

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process a request through the CSRF middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the CSRF middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.CSRFToken(secret=None, token_length=32, max_age=3600)[source]
Parameters:
  • secret (Optional[str])

  • token_length (int)

  • max_age (int)

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

apifrom.security._create_signature(data)

Create a signature for the given data.

param data:

The data to sign

returns:

The signature

apifrom.security.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

apifrom.security.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

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

apifrom.security._add_hsts_header(response)

Add the Strict-Transport-Security header to a response.

param response:

The response to add the header to

apifrom.security._build_hsts_header()

Build the Strict-Transport-Security header value.

returns:

The header value

apifrom.security._get_https_redirect_url(request)

Get the HTTPS redirect URL for a request.

param request:

The request to redirect

returns:

The HTTPS redirect URL

apifrom.security._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

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process a request through the HSTS middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the HSTS middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.HSTSPreloadChecker[source]

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.

apifrom.security.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

apifrom.security.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

class apifrom.security.PermissionsAllowlist[source]

Allowlist values for Permissions Policy directives.

class apifrom.security.PermissionsDirective[source]

Permissions Policy directive constants.

class apifrom.security.PermissionsPolicy[source]

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.

apifrom.security._add_allowlist_value(directive, value)

Add an allowlist value to a directive.

param directive:

The directive name

param value:

The allowlist value

apifrom.security.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

apifrom.security.disable_all()

Disable all features for all origins.

returns:

The policy instance for chaining

apifrom.security.enable_for_self(directives)

Enable specified features for the same origin.

param directives:

The directives to enable

returns:

The policy instance for chaining

apifrom.security.to_header()

Convert the policy to a header value.

returns:

The Permissions-Policy header value

apifrom.security.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

class apifrom.security.PermissionsPolicyBuilder[source]

Helper class for building Permissions Policy.

apifrom.security.create_api_policy()
:staticmethod:

Create a Permissions Policy suitable for APIs.

returns:

A Permissions Policy for APIs

apifrom.security.create_minimal_policy()
:staticmethod:

Create a minimal Permissions Policy that disables sensitive features.

returns:

A minimal Permissions Policy

apifrom.security.create_strict_policy()
:staticmethod:

Create a strict Permissions Policy that disables all features.

returns:

A strict Permissions Policy

apifrom.security.create_web_policy()
:staticmethod:

Create a Permissions Policy suitable for web applications.

returns:

A Permissions Policy for web applications

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

apifrom.security._create_default_policy()

Create a default Permissions Policy.

returns:

A default Permissions Policy

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process a request through the Permissions Policy middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the Permissions Policy middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.SRIBuilder[source]

Helper class for building SRI policies.

apifrom.security.create_common_cdn_policy()
:staticmethod:

Create an SRI policy for common CDN resources.

returns:

An SRI policy for common CDN resources

apifrom.security.create_empty_policy()
:staticmethod:

Create an empty SRI policy.

returns:

An empty SRI policy

apifrom.security.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

class apifrom.security.SRIGenerator[source]

Utility for generating Subresource Integrity hashes.

apifrom.security.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’

apifrom.security.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

apifrom.security.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

SRIHashAlgorithm:bases: enum.Enum

Hash algorithms supported by Subresource Integrity.

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

apifrom.security._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

apifrom.security._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

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process a request through the SRI middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the SRI middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.SRIPolicy[source]

Policy for configuring Subresource Integrity.

Initialize the SRI policy.

apifrom.security._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

apifrom.security.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

apifrom.security.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

apifrom.security.compute_missing_integrity_values()
:async:

Compute integrity values for sources that don’t have them.

returns:

The SRI policy instance for chaining

apifrom.security.enable_verification(enable=True)

Enable or disable verification of external resources.

param enable:

Whether to enable verification

returns:

The SRI policy instance for chaining

apifrom.security.set_algorithms(algorithms)

Set the hash algorithms to use.

param algorithms:

The hash algorithms to use

returns:

The SRI policy instance for chaining

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._add_security_headers(response)

Add security headers to a response.

param response:

The response to add headers to

apifrom.security._build_permissions_policy()

Build the Permissions-Policy header value.

returns:

The Permissions-Policy header value

apifrom.security._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.process_request(request)
:async:

Process a request through the security headers middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the security headers middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.TrustedTypesBuilder[source]

Helper class for building Trusted Types policies.

apifrom.security.create_default_policy()
:staticmethod:

Create a default Trusted Types policy.

returns:

A default Trusted Types policy

apifrom.security.create_escape_policy()
:staticmethod:

Create a Trusted Types policy that escapes HTML.

returns:

A Trusted Types policy that escapes HTML

apifrom.security.create_sanitize_policy()
:staticmethod:

Create a Trusted Types policy that sanitizes HTML.

returns:

A Trusted Types policy that sanitizes HTML

apifrom.security.create_url_policy()
:staticmethod:

Create a Trusted Types policy for URLs.

returns:

A Trusted Types policy for URLs

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

apifrom.security._generate_policy_script()

Generate a script to create Trusted Types policies.

returns:

A script element with the policy creation code

apifrom.security._get_csp_header_name()

Get the CSP header name based on the mode.

returns:

The CSP header name

apifrom.security._get_csp_header_value()

Get the CSP header value for Trusted Types.

returns:

The CSP header value

apifrom.security._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

apifrom.security._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

apifrom.security.process_request(request)
:async:

Process a request through the Trusted Types middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the Trusted Types middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.TrustedTypesPolicy(name, enforce=True)[source]
Parameters:

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

apifrom.security.add_html_handler(handler)

Add an HTML handler.

param handler:

The handler function

returns:

The policy instance for chaining

apifrom.security.add_script_handler(handler)

Add a script handler.

param handler:

The handler function

returns:

The policy instance for chaining

apifrom.security.add_script_url_handler(handler)

Add a script URL handler.

param handler:

The handler function

returns:

The policy instance for chaining

apifrom.security.add_url_handler(handler)

Add a URL handler.

param handler:

The handler function

returns:

The policy instance for chaining

apifrom.security.create_html(html)

Create trusted HTML.

param html:

The HTML to create

returns:

The trusted HTML

apifrom.security.create_script(script)

Create a trusted script.

param script:

The script to create

returns:

The trusted script

apifrom.security.create_script_url(url)

Create a trusted script URL.

param url:

The URL to create

returns:

The trusted script URL

apifrom.security.create_url(url)

Create a trusted URL.

param url:

The URL to create

returns:

The trusted URL

apifrom.security.to_js()

Convert the policy to JavaScript code.

returns:

JavaScript code for creating the policy

class apifrom.security.TrustedTypesViolationReporter(report_uri, callback=None)[source]
Parameters:
  • report_uri (str)

  • callback (Optional[Callable[[Dict[str, Any]], 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

apifrom.security.get_report_uri()

Get the report URI.

returns:

The report URI

apifrom.security.handle_report(report)
:async:

Handle a Trusted Types violation report.

param report:

The violation report

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._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._sanitize_response(response)

Sanitize a response to prevent XSS attacks.

param response:

The response to sanitize

apifrom.security.process_request(request)
:async:

Process a request through the XSS protection middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.process_response(response)
:async:

Process a response through the XSS protection middleware.

param response:

The response to process

returns:

The processed response

Functions

apifrom.security.api_key_required(func=None, *, api_keys=None, scopes=None, error_message='Invalid or missing API key')[source]
Parameters:
  • api_keys (Optional[Dict[str, Union[str, List[str], Dict[str, Any]]]])

  • scopes (Optional[List[str]])

  • error_message (str)

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.

apifrom.security.basic_auth_required(func=None, *, credentials=None, error_message='Invalid or missing credentials')[source]
Parameters:
  • credentials (Optional[Dict[str, str]])

  • error_message (str)

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.

apifrom.security.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')[source]
Parameters:
  • secret (Optional[str])

  • algorithm (Optional[str])

  • verify_exp (bool)

  • verify_aud (bool)

  • audience (Optional[str])

  • verify_iss (bool)

  • issuer (Optional[str])

  • verify_sub (bool)

  • subject (Optional[str])

  • required_claims (Optional[List[str]])

  • optional_claims (Optional[List[str]])

  • error_message (str)

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

apifrom.security.oauth2_required(func=None, *, scopes=None, token_url=None, error_message='Invalid or missing OAuth2 token')[source]
Parameters:
  • scopes (Optional[List[str]])

  • token_url (Optional[str])

  • error_message (str)

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.