### Install django-permissions-policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Install the package using pip. ```sh python -m pip install django-permissions-policy ``` -------------------------------- ### Internal Feature Names Initialization Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Provides example values for the _FEATURE_NAMES set, illustrating the types of permissions policy features supported. ```python _FEATURE_NAMES = { "accelerometer", "ambient-light-sensor", "autoplay", "camera", "geolocation", "microphone", "payment", "usb", # ... and many others } ``` -------------------------------- ### Permissions-Policy Header Example Values Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Provides example values for the Permissions-Policy header, illustrating feature-to-origin mappings. ```plaintext camera=(self), geolocation=(), microphone=(self "https://example.com") ``` -------------------------------- ### Basic Middleware Installation Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt Install the PermissionsPolicyMiddleware in your Django project's settings.py to enable the Permissions-Policy header for all responses. ```python MIDDLEWARE = [ # ... other middleware ... "django_permissions_policy.middleware.PermissionsPolicyMiddleware", # ... other middleware ... ] ``` -------------------------------- ### Compute Header Value Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md This example demonstrates how to use the compute_header_value static method to generate a Permissions-Policy header string from a configuration dictionary. It shows the expected output format. ```python from django_permissions_policy import PermissionsPolicyMiddleware config = { "geolocation": [], "camera": "self", "microphone": ["self", "https://trusted.example.com"], } header_value = PermissionsPolicyMiddleware.compute_header_value( config, setting_name="PERMISSIONS_POLICY" ) print(header_value) # Output: camera=(self), geolocation=(), microphone=(self "https://trusted.example.com") ``` -------------------------------- ### Development Configuration Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Configure PERMISSIONS_POLICY in settings.py for development. Django will fail immediately on invalid configurations, helping catch typos early. ```python # settings.py (development) PERMISSIONS_POLICY = { "camera": "self", "microphone": "self", "geolocation": [], } ``` -------------------------------- ### Minimal Restrictive Settings Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Example of a minimal restrictive Permissions-Policy configuration in Django settings. This sets a baseline for security. ```python settings.py PERMISSIONS_POLICY = { "camera": "()", "microphone": "()", } ``` -------------------------------- ### Relaxed Policy Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Configure a more relaxed default Permissions-Policy using the `PERMISSIONS_POLICY` Django setting. This example allows certain features like 'self'. ```python settings.py PERMISSIONS_POLICY = { "camera": "self", "microphone": "self", "display-capture": "self", "picture-in-picture": "self", "sync-xhr-upload": "self", "web-share": "self", "payment": "self", "fullscreen": "self", } ``` -------------------------------- ### Example Permissions-Policy Header Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md This is an example of the Permissions-Policy header that the library automatically adds to responses. Browsers use this header to enforce policies restricting JavaScript feature access. ```http Permissions-Policy: camera=(self), geolocation=(), microphone=(self "https://trusted.example.com") ``` -------------------------------- ### Allow Everything Policy Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Configure a default Permissions-Policy that allows all features using the `PERMISSIONS_POLICY` Django setting. This is generally not recommended for security reasons. ```python settings.py PERMISSIONS_POLICY = { "*": "*", } ``` -------------------------------- ### Test New Policy in Report-Only Settings Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Example of configuring a new policy in report-only mode using Django settings. This allows testing the policy's impact without enforcing it. ```python settings.py PERMISSIONS_POLICY_REPORT_ONLY = { "interest-cohort": "வியை:https://trusted.example.com" } ``` -------------------------------- ### Example of Unknown Feature Name in Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Demonstrates a typo in a feature name within the `PERMISSIONS_POLICY` setting, which will lead to an `ImproperlyConfigured` exception. ```python PERMISSIONS_POLICY = { "accelerometor": "self", # Typo: should be "accelerometer" } ``` -------------------------------- ### Feature-Specific Overrides with Decorators Settings Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Example demonstrating how to use decorators to override the default Permissions-Policy defined in Django settings for specific views. This allows for granular control. ```python settings.py PERMISSIONS_POLICY = { "camera": "()", "microphone": "()", } # views.py from django.http import HttpResponse from permissions_policy import permissions_policy @permissions_policy("camera") def view_with_camera_access(request): return HttpResponse("Camera access allowed.") def view_without_camera_access(request): return HttpResponse("Camera access denied.") ``` -------------------------------- ### Strict Default Policy Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Configure a strict default Permissions-Policy using the `PERMISSIONS_POLICY` Django setting. This example restricts most features by default. ```python settings.py PERMISSIONS_POLICY = { "camera": "()", "microphone": "()", "display-capture": "()", "picture-in-picture": "()", "sync-xhr-upload": "()", "web-share": "()", "payment": "()", "fullscreen": "()", } ``` -------------------------------- ### Complete Permissions Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Configure the Permissions-Policy header globally in settings.py. This example disables sensitive APIs and restricts others, while also setting a report-only policy for display capture. ```python # settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ] PERMISSIONS_POLICY = { # Disable sensitive APIs "accelerometer": [], "ambient-light-sensor": [], "camera": [], "geolocation": [], "gyroscope": [], "magnetometer": [], "microphone": [], "midi": [], "usb": [], # Restrict privacy-impacting features "interest-cohort": [], # Disable FLoC "unload": [], # Prevent unload events # Allow some features from self "fullscreen": "self", "payment": ["self"], } PERMISSIONS_POLICY_REPORT_ONLY = { "display-capture": [], } ``` ```python # views.py from django_permissions_policy.decorators import permissions_policy_override @permissions_policy_override({"camera": ["self"]}) def video_call_view(request): return render(request, "video/call.html") @permissions_policy_override({}) # No header def no_policy_view(request): return render(request, "no_policy.html") ``` -------------------------------- ### Allow Specific Trusted Origins Settings Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Example of a Permissions-Policy configuration in Django settings that allows specific trusted origins for certain features. This is useful for integrating with third-party services. ```python settings.py PERMISSIONS_POLICY = { "camera": "()", "microphone": "()", "display-capture": "()", "picture-in-picture": "()", "sync-xhr-upload": "()", "web-share": "()", "payment": "()", "fullscreen": "()", "interest-cohort": "வியை:https://trusted.example.com" } ``` -------------------------------- ### Relaxed Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Configure a relaxed policy allowing specific features from trusted origins. This example allows camera and microphone from the same origin, and geolocation from both the same origin and a trusted external domain. ```python PERMISSIONS_POLICY = { "camera": ["self"], "geolocation": ["self", "https://trusted.example.com"], "microphone": ["self"], } ``` -------------------------------- ### Internal Feature Names Usage Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Demonstrates how the _FEATURE_NAMES set is used to validate feature names provided in the configuration, raising an error for unknown features. ```python if feature not in _FEATURE_NAMES: raise ImproperlyConfigured( f"Unknown feature '{feature}' in {setting_name}" ) ``` -------------------------------- ### Example Fix for Invalid Decorator Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Provides an example of how to fix an `ImproperlyConfigured` error caused by an invalid Permissions-Policy configuration in a decorator. The fix involves correcting the feature name or origin format. ```python # Incorrect configuration (causes ImproperlyConfigured error) # @permissions_policy("invalid-feature") # Corrected configuration from django.http import HttpResponse from permissions_policy import permissions_policy @permissions_policy("camera") # Corrected feature name def my_view(request): return HttpResponse("Hello, world!") ``` -------------------------------- ### Configure Report-Only Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Set a report-only policy to test its effects without enforcing it. This example disables geolocation and sets a report-only policy for autoplay. ```python PERMISSIONS_POLICY = { "geolocation": [], } PERMISSIONS_POLICY_REPORT_ONLY = { "autoplay": ["self", "https://archive.org"], } ``` -------------------------------- ### Middleware __call__ Method Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md The middleware is automatically invoked by Django. Direct invocation within application code is not required. ```python # The middleware is called automatically by Django # No direct invocation needed in application code ``` -------------------------------- ### Test Relaxed Policy with Report-Only Header Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md This example demonstrates using both PERMISSIONS_POLICY and PERMISSIONS_POLICY_REPORT_ONLY. It disables camera and microphone globally while testing a relaxed policy for camera and fullscreen in report-only mode. ```python PERMISSIONS_POLICY = { "camera": [], "microphone": [], } PERMISSIONS_POLICY_REPORT_ONLY = { "camera": ["self"], "fullscreen": ["self", "https://streaming.example.com"], } ``` -------------------------------- ### Configure PermissionsPolicyMiddleware in Django Settings Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md Example of how to add PermissionsPolicyMiddleware to your Django project's MIDDLEWARE setting and define the PERMISSIONS_POLICY for HTTP headers. ```python # In Django settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", # ... other middleware ] PERMISSIONS_POLICY = { "geolocation": [], "microphone": ["self"], "camera": ["self", "https://trusted.example.com"], } ``` -------------------------------- ### International Domain Names Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Demonstrates the use of Unicode characters in origin values for Permissions-Policy, specifically for internationalized domain names (IDNs). Ensure proper encoding if necessary. ```python settings.py PERMISSIONS_POLICY = { "camera": "வியை:https://例子.测试" } ``` -------------------------------- ### Configure Strict Permissions Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Set a strict Permissions-Policy to disable privacy-invading features for all scripts. This example disables many features by default. ```python PERMISSIONS_POLICY = { "accelerometer": [], "ambient-light-sensor": [], "autoplay": [], "camera": [], "display-capture": [], "encrypted-media": [], "fullscreen": [], "geolocation": [], "gyroscope": [], "interest-cohort": [], "magnetometer": [], "microphone": [], "midi": [], "payment": [], "usb": [], } ``` -------------------------------- ### Handling ImproperlyConfigured Errors in a Management Command Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Provides an example of how to catch and handle `ImproperlyConfigured` exceptions that may arise during middleware initialization in a Django management command. This allows for graceful error reporting. ```python from django.core.management.base import BaseCommand from django.core.exceptions import ImproperlyConfigured class Command(BaseCommand): def handle(self, *args, **options): try: # Some operation that might trigger middleware initialization from django.test.client import Client client = Client() response = client.get("/") except ImproperlyConfigured as e: self.stderr.write(f"Configuration error: {e}") return 1 return 0 ``` -------------------------------- ### Permissions-Policy Header Example Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/README.md Illustrates the structure of the HTTP Permissions-Policy header, specifying allowed browser features and their origins. This header is used to control which features are allowed to be used by the document and its sub-resources. ```http Permissions-Policy: camera=(self), geolocation=(), payment=("https://example.com") ``` -------------------------------- ### Testing ImproperlyConfigured Exception with Pytest Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Provides a pytest example using `override_settings` to test that an `ImproperlyConfigured` exception is raised when an unknown feature is present in `PERMISSIONS_POLICY`. ```python import pytest from django.core.exceptions import ImproperlyConfigured from django.test import override_settings def test_invalid_feature_raises(): with override_settings(PERMISSIONS_POLICY={"unknown": []}): with pytest.raises(ImproperlyConfigured, match="Unknown feature"): # Force middleware instantiation or request processing client.get("/") ``` -------------------------------- ### Combine Enforced and Report-Only Policy Overrides Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-decorators.md This example shows how to use both `permissions_policy_override` and `permissions_policy_report_only_override` decorators on the same view. The enforced policy (`geolocation`) will be applied, while the report-only policy (`camera`) will be simulated and reported without enforcement. ```python from django.shortcuts import render from django_permissions_policy.decorators import ( permissions_policy_override, permissions_policy_report_only_override, ) @permissions_policy_override({"geolocation": []}) @permissions_policy_report_only_override({"camera": []}) def restricted_view(request): """ This view: - Disables geolocation entirely (enforced) - Tests camera disable in report-only mode (simulated, not enforced) """ return render(request, "restricted.html") ``` -------------------------------- ### Internal Usage Example: Applying Permissions Policy Override Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Illustrates how the internal _apply_headers method checks for and applies the pre-computed header value from the _permissions_policy_override attribute on a response object. ```python # In _apply_headers method if hasattr(response, "_permissions_policy_override"): if response._permissions_policy_override: response["Permissions-Policy"] = response._permissions_policy_override ``` -------------------------------- ### View with Invalid Permissions Policy Decorator Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-decorators.md This example demonstrates how an invalid configuration passed to the `permissions_policy_override` decorator will raise an `ImproperlyConfigured` error at import time. ```python from django.core.exceptions import ImproperlyConfigured from django_permissions_policy.decorators import permissions_policy_override # This raises ImproperlyConfigured immediately when the module is loaded @permissions_policy_override({"invalid-feature": []}) def broken_view(request): pass ``` -------------------------------- ### Example of Decorating a Django View with Type Preservation Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Demonstrates the practical application of the _ViewFunc type variable by decorating a Django view function. Type checkers will recognize that 'my_view' retains its original function type after decoration. ```python from django.shortcuts import render from django_permissions_policy.decorators import permissions_policy_override # Type checker recognizes this as a function view @permissions_policy_override({"camera": []}) def my_view(request): return render(request, "template.html") # Type of my_view is still a function, not an opaque 'Any' ``` -------------------------------- ### Basic Usage Pattern Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/README.md Demonstrates the typical integration steps: adding middleware, configuring settings, and optionally overriding policies with decorators. ```python # 1. Add middleware MIDDLEWARE = ["django_permissions_policy.PermissionsPolicyMiddleware"] # 2. Configure policy PERMISSIONS_POLICY = {"camera": [], "microphone": "self"} # 3. Override on specific views (optional) @permissions_policy_override({"camera": ["self"]}) def video_view(request): pass # 4. Decorators are validated at import time (no runtime errors) # 5. Middleware applies headers automatically ``` -------------------------------- ### Allow Everything Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Configure a policy that allows all features from any origin. Use this cautiously as it provides minimal security. ```python PERMISSIONS_POLICY = { "accelerometer": "*", "camera": "*", "geolocation": "*", "microphone": "*", } ``` -------------------------------- ### PermissionsPolicyMiddleware Constructor Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md Initializes the PermissionsPolicyMiddleware. It accepts a get_response callable, detects async mode, pre-evaluates policy settings, and registers a signal handler for setting changes. ```APIDOC ## PermissionsPolicyMiddleware Constructor ### Description Initializes the PermissionsPolicyMiddleware, setting up the request/response handling chain and configuring policy headers based on Django settings. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # In Django settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", # ... other middleware ] PERMISSIONS_POLICY = { "geolocation": [], "microphone": ["self"], "camera": ["self", "https://trusted.example.com"], } ``` ### Response #### Success Response (200) This method does not directly return a response; it initializes the middleware. #### Response Example None ### Raises - `ImproperlyConfigured`: If `PERMISSIONS_POLICY` or `PERMISSIONS_POLICY_REPORT_ONLY` settings contain invalid feature names or malformed values. ``` -------------------------------- ### PermissionsPolicyMiddleware Initialization Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt The PermissionsPolicyMiddleware constructor initializes the policy based on Django settings. Ensure PERMISSIONS_POLICY is correctly configured. ```python class PermissionsPolicyMiddleware: def __init__(self, get_response): self.get_response = get_response self.policy = PermissionsPolicy(settings.PERMISSIONS_POLICY) self.report_only_policy = PermissionsPolicy( settings.PERMISSIONS_POLICY_REPORT_ONLY, is_report_only=True ) self._feature_names = _FEATURE_NAMES def __call__(self, request): response = self.get_response(request) response["Permissions-Policy"] = self.policy.header_value if self.report_only_policy.header_value: response["Permissions-Policy-Report-Only"] = ( self.report_only_policy.header_value ) return response ``` -------------------------------- ### Override Permissions Policy for a View Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Use the `permissions_policy_override` decorator to set a specific Permissions-Policy header for a single view. This example disables geolocation. ```python from django.shortcuts import render from django_permissions_policy.decorators import permissions_policy_override @permissions_policy_override( { "geolocation": [], } ) def puppy_park_view(request): return render(request, "puppies/park.html") ``` -------------------------------- ### Allow Autoplay from All Origins Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Use a wildcard '*' to allow a permission from any origin. ```python PERMISSIONS_POLICY = { "autoplay": "*", } ``` -------------------------------- ### PermissionsPolicyMiddleware.__call__ Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md The synchronous entry point for the middleware, handling requests and applying headers. ```APIDOC ## `__call__(request: HttpRequest) -> HttpResponseBase | Awaitable[HttpResponseBase]` ### Description Entry point for the middleware. If `async_mode` is `True`, delegates to `__acall__()` and returns an awaitable. Otherwise, directly processes the request synchronously and applies headers via `_apply_headers()`. ### Method `__call__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # The middleware is called automatically by Django # No direct invocation needed in application code ``` ### Response #### Success Response `HttpResponseBase | Awaitable[HttpResponseBase]` — The HTTP response object with headers applied, or an awaitable that resolves to a response in async mode. #### Response Example None provided. ``` -------------------------------- ### Dynamic Configuration with override_settings Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Demonstrates how to dynamically change the PERMISSIONS_POLICY setting in tests or runtime code using Django's `override_settings` context manager. The middleware automatically picks up these changes. ```python from django.test import override_settings # In tests or dynamic code with override_settings(PERMISSIONS_POLICY={"camera": ["self"]}): response = client.get("/some-view/") # Response has Permissions-Policy header # Outside the context manager response = client.get("/some-view/") # Response has original PERMISSIONS_POLICY or no header if not set ``` -------------------------------- ### Configure Site-Wide Permissions Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/README.md Add the middleware to your settings and define the default PERMISSIONS_POLICY dictionary. ```python # settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ] PERMISSIONS_POLICY = { "camera": [], "microphone": ["self"], "geolocation": ["self", "https://trusted.example.com"], } ``` -------------------------------- ### Override Report-Only Permissions Policy for a View Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Use the `permissions_policy_report_only_override` decorator to set a specific Permissions-Policy-Report-Only header for a single view. This example tests a policy restricting autoplay. ```python from django.shortcuts import render from django_permissions_policy.decorators import permissions_policy_report_only_override @permissions_policy_report_only_override( { "autoplay": [], } ) def puppy_tricks_view(request): return render(request, "puppies/tricks.html") ``` -------------------------------- ### PermissionsPolicyMiddleware Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt Documentation for the PermissionsPolicyMiddleware class, including its constructor and all 8 methods. ```APIDOC ## PermissionsPolicyMiddleware ### Description Provides middleware functionality for enforcing Permissions-Policy headers. ### Constructor #### Parameters - **get_response** (Callable) - Required - The next middleware or view in the stack. - **permissions_policy** (Dict[str, str] | None) - Optional - The default Permissions-Policy header value. - **permissions_policy_report_only** (Dict[str, str] | None) - Optional - The default Permissions-Policy-Report-Only header value. ### Methods #### __init__(self, get_response, permissions_policy=None, permissions_policy_report_only=None) Initializes the middleware with the get_response callable and optional policy configurations. #### __call__(self, request) Synchronously processes an incoming request. #### __acall__(self, request) Asynchronously processes an incoming request. #### compute_header_value(policy, request) (static method) Computes the final Permissions-Policy header value based on the policy and request. #### permissions_policy(self) (cached_property) Returns the resolved Permissions-Policy header value for the request. #### permissions_policy_report_only(self) (cached_property) Returns the resolved Permissions-Policy-Report-Only header value for the request. #### _apply_headers(self, request, response) Applies the computed Permissions-Policy headers to the response. #### clear_header_value(self) Clears any cached header values. ``` -------------------------------- ### Configure Multiple Features with Permissions Policy Override Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-decorators.md Configure multiple features like 'camera', 'microphone', and 'geolocation' with specific origin allowances using `permissions_policy_override`. This allows fine-grained control over browser feature access per view. ```python from django.shortcuts import render from django_permissions_policy.decorators import permissions_policy_override @permissions_policy_override({ "camera": ["self"], "microphone": ["self", "https://trusted.example.com"], "geolocation": [], }) def video_call_view(request): """View allowing camera and microphone from specific origins.""" return render(request, "video/call.html") ``` -------------------------------- ### Import PermissionsPolicyMiddleware Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/README.md Import the necessary middleware class for integrating with Django. ```python from django_permissions_policy import PermissionsPolicyMiddleware ``` -------------------------------- ### Catch Invalid Configuration in Middleware Initialization Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Illustrates how to catch `ImproperlyConfigured` errors that occur during Django startup due to invalid configuration in the Permissions-Policy middleware. This typically happens when the middleware is initialized. ```python from django.core.exceptions import ImproperlyConfigured from django.test import TestCase class MiddlewareConfigTests(TestCase): def test_middleware_invalid_config(self): with self.assertRaises(ImproperlyConfigured) as cm: # Simulate middleware initialization with invalid settings # This would typically be caught by Django's startup process pass # Replace with actual middleware initialization simulation if possible self.assertIn("Invalid configuration", str(cm.exception)) ``` -------------------------------- ### Testing New Policies in Report-Only Mode Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Configure both a default `PERMISSIONS_POLICY` and a `PERMISSIONS_POLICY_REPORT_ONLY` in settings.py. This allows you to test new policy configurations without enforcing them, as violations will only be reported. ```python PERMISSIONS_POLICY = { "camera": ["self"], "microphone": ["self"], } PERMISSIONS_POLICY_REPORT_ONLY = { "camera": [], "microphone": [], "geolocation": [], } ``` -------------------------------- ### Triggering ImproperlyConfigured with Invalid Feature Name Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md This example demonstrates how applying a decorator with an unknown feature name will raise an ImproperlyConfigured error at import time. Ensure feature names are correctly spelled and defined. ```python from django_permissions_policy.decorators import permissions_policy_override # This raises ImproperlyConfigured when the module is imported @permissions_policy_override({"unknown-feature": []}) def bad_view(request): pass ``` -------------------------------- ### Fixing Invalid Feature Name in Decorator Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md This example shows the correction of a typo in a feature name within a decorator's configuration. Always verify feature names against the valid features list to prevent configuration errors. ```python # Before (error) @permissions_policy_override({"camra": "self"}) def my_view(request): pass # After (fixed) @permissions_policy_override({"camera": "self"}) def my_view(request): pass ``` -------------------------------- ### List of Origins Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Configure a feature with multiple allowed origins using a list. ```python config = {"camera": ["self", "https://example.com"]} ``` -------------------------------- ### Testing Permissions Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/README.md Shows how to test the Permissions-Policy header using Django's test utilities and `override_settings`. ```python from django.test import override_settings with override_settings(PERMISSIONS_POLICY={"camera": ["self"]}): response = client.get("/view/") assert response["Permissions-Policy"] == "camera=(self)" ``` -------------------------------- ### PermissionsPolicyMiddleware.__acall__ Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md The asynchronous entry point for the middleware, used in async mode to handle requests. ```APIDOC ## `__acall__(request: HttpRequest) -> Awaitable[HttpResponseBase]` ### Description Async entry point for the middleware. Called when `async_mode` is `True`. Awaits the `get_response()` callable and then applies headers via `_apply_headers()`. ### Method `__acall__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None provided. ### Response #### Success Response `HttpResponseBase` — The HTTP response object with headers applied. #### Response Example None provided. ``` -------------------------------- ### Permissions Policy Override: Wildcard (Allow All) Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-decorators.md Use a wildcard '*' to allow all origins for a given permission policy feature. ```python @permissions_policy_override({"fullscreen": "*"}) ``` -------------------------------- ### Creating a Custom Decorator Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt The _make_decorator helper function simplifies creating custom decorators for the Permissions Policy. It handles the logic for applying policy overrides. ```python def _make_decorator(policy_dict, is_report_only=False): def decorator(view): @functools.wraps(view) def wrapper(request, *args, **kwargs): policy = PermissionsPolicy(policy_dict, is_report_only=is_report_only) response = view(request, *args, **kwargs) response["Permissions-Policy"] = policy.header_value return response return wrapper return decorator ``` -------------------------------- ### Middleware Constructor Type Annotations Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Defines the type hint for the get_response parameter in the middleware constructor, supporting both synchronous WSGI and asynchronous ASGI handlers. ```python def __init__( self, get_response: ( Callable[[HttpRequest], HttpResponseBase] | Callable[[HttpRequest], Awaitable[HttpResponseBase]] ), ) -> None ``` -------------------------------- ### Django Settings Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt Configuration options for django-permissions-policy via Django settings. ```APIDOC ## Django Settings ### PERMISSIONS_POLICY - **Type**: Dict[str, str] | None - **Description**: Default Permissions-Policy header value for the entire project. ### PERMISSIONS_POLICY_REPORT_ONLY - **Type**: Dict[str, str] | None - **Description**: Default Permissions-Policy-Report-Only header value for the entire project. ``` -------------------------------- ### Multiple Features Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Configure multiple features within a single dictionary, specifying origins or disabling features as needed. ```python config = { "camera": ["self"], "microphone": "self", "geolocation": [], "payment": ["https://payment.example.com"], } ``` -------------------------------- ### Tuple of Origins Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Configure a feature with multiple allowed origins using a tuple. Lists are generally preferred. ```python config = {"camera": ("self", "https://example.com")} ``` -------------------------------- ### View-Specific Override with No Default Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Demonstrates how to apply a policy override to a specific view using the `@permissions_policy_override` decorator when no global `PERMISSIONS_POLICY` is set in `settings.py`. Other views will not have any policy headers set. ```python # settings.py - empty or not set PERMISSIONS_POLICY # views.py @permissions_policy_override({"camera": "self"}) def only_on_this_view(request): return render(request, "specific.html") def everywhere_else(request): # No header set return render(request, "other.html") ``` -------------------------------- ### Catch Unknown Feature Name Error Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Demonstrates how to catch an `ImproperlyConfigured` error that occurs at import time when an unknown feature name is used in the Permissions-Policy configuration. This helps in identifying and fixing configuration issues early. ```python from django.core.exceptions import ImproperlyConfigured try: from myapp.views import my_view # Assuming my_view uses an invalid feature name except ImproperlyConfigured as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Add PermissionsPolicyMiddleware to settings.py Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Integrate the PermissionsPolicyMiddleware into your Django project's settings by adding it to the MIDDLEWARE list. This ensures the header is applied to all responses. ```python MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ] ``` -------------------------------- ### Single String Origin Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/types.md Configure a feature with a single allowed origin. This will be automatically converted to a list internally. ```python config = {"camera": "self"} ``` -------------------------------- ### Async View with Permissions Policy Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt Use the Permissions-Policy decorator with asynchronous Django views. Ensure your view function is defined with `async def`. ```python from django.http import HttpResponse from permissions_policy import permissions_policy @permissions_policy("fullscreen") async def my_async_view(request): return HttpResponse("Hello, world!") ``` -------------------------------- ### Strict Default Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Use this configuration to set a strict default policy, disabling all features. This is useful for a baseline security posture. ```python PERMISSIONS_POLICY = { "accelerometer": [], "ambient-light-sensor": [], "autoplay": [], "camera": [], "display-capture": [], "encrypted-media": [], "fullscreen": [], "geolocation": [], "gyroscope": [], "magnetometer": [], "microphone": [], "midi": [], "payment": [], "usb": [], } ``` -------------------------------- ### Catching ImproperlyConfigured Exception Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Shows a basic try-except block to catch `ImproperlyConfigured` exceptions. Note that this specific error typically occurs at Django startup. ```python from django.core.exceptions import ImproperlyConfigured try: # This happens at Django startup, not runtime, so catching here is not typical pass except ImproperlyConfigured as e: print(f"Invalid configuration: {e}") ``` -------------------------------- ### Test New Policy in Report-Only Mode Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Configure both an enforced policy and a report-only policy to test stricter settings without immediate enforcement. Browsers will report violations of the report-only policy. ```python PERMISSIONS_POLICY = { # Current enforced policy "camera": ["self"], "microphone": ["self"], } PERMISSIONS_POLICY_REPORT_ONLY = { # New stricter policy being tested "camera": [], "microphone": [], "geolocation": [], } ``` -------------------------------- ### Basic Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Define the PERMISSIONS_POLICY dictionary in your Django settings to configure browser feature access. ```python PERMISSIONS_POLICY = { "feature-name": "value" or ["value1", "value2"] } ``` -------------------------------- ### Configure PERMISSIONS_POLICY in settings.py Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Define your site-wide permissions policies by configuring the PERMISSIONS_POLICY dictionary in your Django settings. This sets the default policies for all views. ```python PERMISSIONS_POLICY = { "camera": [], "microphone": ["self"], "geolocation": ["self", "https://trusted.example.com"], } ``` -------------------------------- ### Case-Sensitive Feature Name Comparison Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Demonstrates the case-sensitive nature of feature names in Django Permissions Policy configuration. Use the correct casing to avoid `ImproperlyConfigured` errors. ```python # Wrong "Camera": [] # ImproperlyConfigured # Correct "camera": [] # Valid ``` -------------------------------- ### ImproperlyConfigured: Unknown feature name Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Illustrates an `ImproperlyConfigured` error raised when an unknown feature name is present in the PERMISSIONS_POLICY setting. Ensure all feature names are recognized by the library. ```python PERMISSIONS_POLICY = {"unknown-feature": []} # Raises: ImproperlyConfigured("Unknown feature 'unknown-feature' in PERMISSIONS_POLICY") ``` -------------------------------- ### Define Permissions Policy with Unicode Origins Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Use this format to define your Permissions-Policy settings, including support for Unicode characters in origin URLs. The middleware handles the necessary quoting. ```python PERMISSIONS_POLICY = { "camera": ["https://example.com", "https://例え.jp"], } # The middleware will wrap these in quotes correctly ``` -------------------------------- ### Allow Autoplay from Specific Origins Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Specify allowed origins, including 'self' for the current origin and specific domains, for a permission. ```python PERMISSIONS_POLICY = { "autoplay": ["self", "https://archive.org"], } ``` -------------------------------- ### Permissions Policy Override: List of Values Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-decorators.md Configure a permission policy feature to allow access from multiple origins by providing a list of values. ```python @permissions_policy_override({"microphone": ["self", "https://trusted.example.com"]}) ``` -------------------------------- ### PermissionsPolicyMiddleware Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/TABLE_OF_CONTENTS.txt The PermissionsPolicyMiddleware is the primary entry point for applying Permissions-Policy headers to responses. It can be configured via Django settings and automatically handles asynchronous and synchronous requests. ```APIDOC ## PermissionsPolicyMiddleware ### Description This middleware automatically applies the `Permissions-Policy` and `Permissions-Policy-Report-Only` headers to outgoing HTTP responses based on your project's configuration. ### Class `PermissionsPolicyMiddleware` ### Constructor `__init__(self, get_response)` - **get_response** (callable) - Required - The next middleware in the stack or the final view callable. ### Methods #### `__call__(self, request)` - **Description**: Processes an incoming request and applies the appropriate headers to the response. - **Parameters**: - **request** (HttpRequest) - The incoming Django request object. - **Returns**: HttpResponse - The response object with headers applied. #### `__acall__(self, request)` - **Description**: Asynchronous version of `__call__` for ASGI applications. - **Parameters**: - **request** (HttpRequest) - The incoming Django request object. - **Returns**: HttpResponse - The response object with headers applied. #### `compute_header_value(policy, report_only=False)` [STATIC METHOD] - **Description**: Computes the value for the `Permissions-Policy` or `Permissions-Policy-Report-Only` header based on a given policy configuration. - **Parameters**: - **policy** (dict) - A dictionary representing the permissions policy configuration. - **report_only** (bool) - Optional - If True, computes the report-only header value. Defaults to False. - **Returns**: str - The formatted header value string. #### `permissions_policy` [CACHED_PROPERTY] - **Description**: Returns the computed `Permissions-Policy` header value for the current request. #### `permissions_policy_report_only` [CACHED_PROPERTY] - **Description**: Returns the computed `Permissions-Policy-Report-Only` header value for the current request. #### `_apply_headers(self, response, policy_value, report_only_value)` - **Description**: Applies the computed policy and report-only header values to the given response object. - **Parameters**: - **response** (HttpResponse) - The Django response object. - **policy_value** (str) - The value for the `Permissions-Policy` header. - **report_only_value** (str) - The value for the `Permissions-Policy-Report-Only` header. #### `clear_header_value(sender, **kwargs)` - **Description**: Signal handler to clear cached header values, typically used during request teardown. ``` -------------------------------- ### Exception Types Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt Documentation for the ImproperlyConfigured exception. ```APIDOC ## ImproperlyConfigured ### Description Raised when the Permissions-Policy configuration is invalid or missing. ### Error Conditions - Invalid setting values. - Incorrect middleware placement. - Missing required configuration. ``` -------------------------------- ### Mixed Policy Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/index.md Combine different access control methods within the PERMISSIONS_POLICY setting for various features. ```python PERMISSIONS_POLICY = { "camera": ["self"], "geolocation": [], "payment": "self", } ``` -------------------------------- ### Printing Valid Features List for Debugging Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md Shows how to access and print the list of valid feature names supported by the library. This is useful for debugging and verifying correct feature names. ```python from django_permissions_policy import _FEATURE_NAMES print("Valid features:") for feature in sorted(_FEATURE_NAMES): print(f" - {feature}") ``` -------------------------------- ### Feature-Specific Overrides with Decorators Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Use decorators to apply feature-specific permission policy overrides for individual views, overriding the global policy. ```python MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ] PERMISSIONS_POLICY = { "camera": [], "microphone": [], "geolocation": [], } # views.py from django_permissions_policy.decorators import permissions_policy_override @permissions_policy_override({"camera": ["self"]}) def video_call_view(request): # This view allows camera from self, overriding the global policy return render(request, "video/call.html") @permissions_policy_override({"geolocation": ["self"]}) def location_view(request): # This view allows geolocation from self return render(request, "location/map.html") ``` -------------------------------- ### Configuring Permissions Policy via Django Settings Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/GENERATION_REPORT.txt Define the global Permissions-Policy header by setting PERMISSIONS_POLICY in your Django settings. This applies the policy to all responses unless overridden. ```python PERMISSIONS_POLICY = { "geolocation": "(self)", "camera": "(none)", "microphone": "(none)", } PERMISSIONS_POLICY_REPORT_ONLY = { "payment": "(none)" } ``` -------------------------------- ### Configure Permissions Policy Middleware Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/api-reference-middleware.md Add the PermissionsPolicyMiddleware to your Django settings and define the PERMISSIONS_POLICY and PERMISSIONS_POLICY_REPORT_ONLY dictionaries to control feature access. ```python MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ] PERMISSIONS_POLICY = { "accelerometer": [], "ambient-light-sensor": [], "autoplay": [], "camera": [], "geolocation": [], "gyroscope": [], "magnetometer": [], "microphone": [], "payment": [], "usb": [], } PERMISSIONS_POLICY_REPORT_ONLY = { "fullscreen": ["self", "https://trusted.example.com"], } ``` -------------------------------- ### Allow Self for Common Features Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/configuration.md Configure policies to allow access to specific features only from the application's own origin. ```python PERMISSIONS_POLICY = { "camera": "self", "microphone": "self", "geolocation": "self", "fullscreen": "self", } ``` -------------------------------- ### Update PERMISSIONS_POLICY Configuration Source: https://github.com/adamchainz/django-permissions-policy/blob/main/_autodocs/errors.md When migrating between versions, update your PERMISSIONS_POLICY to use current feature names. Old or removed features will raise `ImproperlyConfigured`. ```python # Old configuration (might error in new version) PERMISSIONS_POLICY = { "old-feature": [], # Raises ImproperlyConfigured in new version } # Fixed configuration PERMISSIONS_POLICY = { "new-replacement-feature": [], # Or remove the feature entirely } ``` -------------------------------- ### Add PermissionsPolicyMiddleware to Django Settings Source: https://github.com/adamchainz/django-permissions-policy/blob/main/README.rst Add the middleware to your Django project's MIDDLEWARE setting, preferably after SecurityMiddleware. ```python MIDDLEWARE = [ ... "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", ... ] ```