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

Classes

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.

apifrom.security.headers.options

Options for the middleware.

Type:

dict

Initialize a new BaseMiddleware instance.

param **options:

Options for the middleware.

class apifrom.security.headers.CSPDirective(name)[source]
Parameters:

name (str)

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

class apifrom.security.headers.ContentSecurityPolicy[source]

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

class apifrom.security.headers.ReferrerPolicy[source]

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]
Parameters:
  • request (Optional[starlette.requests.Request])

  • path_params (Optional[dict[Any, Any]])

  • method (Optional[str])

  • path (Optional[str])

  • query_params (Optional[dict[Any, Any]])

  • headers (Optional[dict[Any, Any]])

  • body (Optional[Union[str, bytes]])

  • client_ip (Optional[str])

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]
Parameters:
  • content (Any)

  • status_code (int)

  • headers (Optional[Dict[str, str]])

  • content_type (str)

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

class apifrom.security.headers.XSSFilter[source]

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

class apifrom.security.headers.XSSProtection[source]

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