How authentication works#

class dmr.security.SyncAuth[source]#

Sync auth base class for sync endpoints.

All auth must support initialization without any required parameters. Auth can have non-required parameters with defaults.

abstractmethod __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) → Self | None[source]#

Put your auth business logic here.

Return self if the login attempt was successful. Return None if login attempt failed and we need to try another authes. Raise dmr.exceptions.NotAuthenticatedError to immediately fail the login without trying other authes. Raise dmr.response.APIError if you want to change the return code, for example, when some data is missing or has wrong format.

provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) → list[ResponseSpec]#

Provides responses that can happen when user is not authed.

abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → list[SecurityRequirement]#

Provides a security schema usage requirement.

abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → dict[str, SecurityScheme | Reference]#

Provides a security schema definition.

validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) → None#

Validate auth configuration at import time.

Added in version 0.16.0.

abstract property www_authenticate_challenge: str | None#

Challenge to advertise in WWW-Authenticate on 401 responses.

RFC 9110 Section 15.5.2 requires every 401 to carry at least one challenge, but a challenge can only name an HTTP authentication scheme that the client sends in the Authorization header.

Return None when there is nothing to advertise: auth that reads credentials from a cookie or from a header of its own cannot express itself as a challenge.

Added in version 0.15.0.

class dmr.security.AsyncAuth[source]#

Async auth base class for async endpoints.

All auth must support initialization without any required parameters. Auth can have non-required parameters with defaults.

abstractmethod async __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) → Self | None[source]#

Put your auth business logic here.

Return self if the login attempt was successful. Return None if login attempt failed and we need to try another authes. Raise dmr.exceptions.NotAuthenticatedError to immediately fail the login without trying other authes. Raise dmr.response.APIError if you want to change the return code, for example, when some data is missing or has wrong format.

provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) → list[ResponseSpec]#

Provides responses that can happen when user is not authed.

abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → list[SecurityRequirement]#

Provides a security schema usage requirement.

abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → dict[str, SecurityScheme | Reference]#

Provides a security schema definition.

validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) → None#

Validate auth configuration at import time.

Added in version 0.16.0.

abstract property www_authenticate_challenge: str | None#

Challenge to advertise in WWW-Authenticate on 401 responses.

RFC 9110 Section 15.5.2 requires every 401 to carry at least one challenge, but a challenge can only name an HTTP authentication scheme that the client sends in the Authorization header.

Return None when there is nothing to advertise: auth that reads credentials from a cookie or from a header of its own cannot express itself as a challenge.

Added in version 0.15.0.

final class dmr.security.SyncOrAsyncAuth(_sync_auth: _SyncAuthT, _async_auth: _AsyncAuthT)[source]#

Auth that selects between a sync and async instance.

Use in global settings to apply a single auth rule to both sync and async endpoints. Not allowed on controller or endpoint level.

Added in version 0.11.0.

Changed in version 0.16.0: Now it is generic.

resolve(*, is_async: Literal[True]) → _AsyncAuthT[source]#
resolve(*, is_async: Literal[False]) → _SyncAuthT
resolve(*, is_async: bool) → _AsyncAuthT | _SyncAuthT

Return the auth instance matching is_async requirement.

Changed in version 0.16.0: Replaced auth_cls parameter with simpler is_async.

dmr.security.request_auth(request: HttpRequest, *, strict: Literal[True]) → SyncAuth | AsyncAuth[source]#
dmr.security.request_auth(request: HttpRequest, *, strict: bool = False) → SyncAuth | AsyncAuth | None

Return the auth instance that was used to auth this request.

When strict is passed and request has no auth, we raise AttributeError.

dmr.security.add_www_authenticate(exc: NotAuthenticatedError, auth: Sequence[SyncAuth | AsyncAuth] | None) → None[source]#

Advertise auth in WWW-Authenticate on the 401 that exc returns.

RFC 9110 Section 15.5.2 requires every 401 to carry at least one challenge. Headers that exc already has always win, so an auth class can raise with a challenge of its own.

dmr.security.NO_STORE_HEADERS = mappingproxy({'Cache-Control': NewHeader(description='Credentials must not be stored in any cache.', deprecated=False, example=None, value='no-store')})#
class dmr.security.AuthenticatedHttpRequest[source]#

Annotation for requests that used auth.

Use it for trusted controllers only.

Added in version 0.7.0.

Security#

CSRF#

class dmr.security.csrf.CSRFSemanticSchemaProvider(*, error_model: TypeForm[Any] = <class 'dmr.errors.ErrorModel'>, status_code: HTTPStatus | None = None, description: str | Promise | None = None, security_scheme_name: str = 'csrf', security_header_scheme_name: str = 'csrf_header', safe_http_methods: Set[HTTPMethod] = frozenset({<HTTPMethod.GET>, <HTTPMethod.HEAD>, <HTTPMethod.OPTIONS>, <HTTPMethod.TRACE>}))[source]#

Provide response specs for controllers that have csrf_exempt = False.

Only provides response specs for controllers that set explicit csrf_exempt = False setting and define non-safe HTTP endpoints, like post or put.

Should be added to dmr.settings.Settings.semantic_schema_providers setting.

error_model#

Error model to be returned. Since CSRF is executed in a middleware before any controller, we can’t get the error model from a controller. This is why this has to be configured separately.

Type:

typing_extensions.TypeForm[Any]

status_code#

Status code that should be set for failed CSRF responses.

Type:

http.HTTPStatus | None

description#

Human readable description, what the response is for.

Type:

str | django.utils.functional.Promise | None

security_scheme_name#

Security scheme name for the CSRF cookie/session storage scheme.

Type:

str

csrf_header_scheme_name#

Security scheme name for the CSRF header scheme (cookie mode only, i.e. CSRF_USE_SESSIONS = False).

safe_http_methods#

Set of secure HTTP method names.

Type:

collections.abc.Set[http.HTTPMethod]

Warning

We can’t possibly detect if CSRF enabled for any controller or not. There can be custom middleware, decorators like @csrf_protect, or even ensure_csrf() inline calls.

So, if you know that CSRF is disabled and still want to use csrf_exempt = False for some reason (?), disable this provider from settings.

Added in version 0.16.0.

merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[dict[str, list[str]]], auth_requirements: list[dict[str, list[str]]]) → list[dict[str, list[str]]][source]#

Joins CSRF requirement with each auth requirement.

provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) → list[ResponseSpec][source]#

Returns response specs for CSRF endpoints.

security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → list[dict[str, list[str]]][source]#

Provides a security schema usage requirement.

security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → dict[str, SecurityScheme | Reference][source]#

Provides a security schema definition.

dmr.security.csrf.build_csrf_handler(prefix: str, /, *prefixes: str, serializer: type[BaseSerializer], format_error: ~dmr.internal.types.FormatError = <function format_error>, renderers: ~collections.abc.Sequence[Renderer] | None = None, status_code: ~http.HTTPStatus = HTTPStatus.FORBIDDEN, languages: ~collections.abc.Sequence[str] | None = None) → _CSRFViewProtocol[source]#

Create a CSRF error handler that returns a response with negotiation.

Use this function to build CSRF_FAILURE_VIEW handler in settings.py.

All prefixes are normalized to start with a leading slash. If the request path matches any of them, a REST response is returned using the same serializer and renderers as your API. If the client’s Accept does not match any renderer, the first configured renderer is used. For non-matching paths, Django’s default CSRF_FAILURE_VIEW handler is used.

Parameters:
  • prefix – Path prefix (e.g. 'api/') for which to return API responses.

  • *prefixes – Additional path prefixes.

  • format_error – Callable used to build the error body for the response.

  • serializer – Serializer class used to serialize the error body.

  • renderers – Optional sequence of renderers. If omitted, uses renderers from settings.

  • status_code – Status code to be returned. Defaults to 403.

  • languages – Optional languages that can start the path, like ('en', 'ru') for i18n_patterns. Only these languages are allowed and they must match the path exactly, so en does not match /en-gb/api/. If omitted, all languages of Django are allowed.

Added in version 0.16.0.

Changed in version 0.17.0: Added languages argument.

dmr.security.csrf.csrf_message(reason: str) → str[source]#

Return CSRF failure message according the security rules.

Added in version 0.16.0.

dmr.security.csrf.csrf_response_spec(*, return_type: TypeForm[Any], status_code: HTTPStatus | None = None, description: str | Promise | None = None) → ResponseSpec[source]#

Response spec for CSRF error.

Added in version 0.16.0.

dmr.security.csrf.csrf_security_scheme(scheme_name: str, header_scheme_name: str) → dict[str, SecurityScheme | Reference][source]#

Build the security scheme that describes where the CSRF secret is stored.

By default Django keeps the CSRF secret in the CSRF_COOKIE_NAME cookie, so the scheme is an apiKey in cookie.

With CSRF_USE_SESSIONS = True Django requires to send CSRF in a header (CSRF_HEADER_NAME). In that mode there is no separate cookie scheme; the header alone is the complete requirement.

Parameters:
  • scheme_name – Security scheme name that we use for the CSRF token secret.

  • header_scheme_name – Security scheme name that we use for the CSRF token value.

Added in version 0.16.0.

Changed in version 0.17.0: Now this function returns a dict object of schemes. And accepts the names for these schemes. Now when CSRF_USE_SESSIONS is defined, we return the header security scheme.

class dmr.security.csrf.CSRFAuthMixin[source]#

Shared parts of auth classes that are protected by CSRF.

This mixin does all of it. Subclasses only have to:

  • set security_scheme_name, csrf_scheme_name, and csrf_header_scheme_name attributes,

  • implement auth_security_scheme() with their own scheme,

  • call _ensure_csrf from __call__ at the right moment.

Must be listed before the concrete auth base in the class bases, so the methods here win over the default ones.

Added in version 0.16.0.

abstractmethod auth_security_scheme() → SecurityScheme[source]#

Provides the security scheme of the auth itself, without CSRF.

csrf_security_scheme() → dict[str, SecurityScheme | Reference][source]#

Provides the security scheme for CSRF cookie/session storage.

Changed in version 0.17.0: Now this method returns a dict object of schemes. Now when CSRF_USE_SESSIONS is defined, we return the header security scheme.

provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) → list[ResponseSpec][source]#

Declares extra responses for failed auth and failed CSRF checks.

security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → list[dict[str, list[str]]][source]#

Requires the auth scheme and CSRF for unsafe HTTP methods.

security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → dict[str, SecurityScheme | Reference][source]#

Provides the auth security scheme together with the CSRF one(s).

property www_authenticate_challenge: str | None#

This auth has no challenge to advertise, so this returns None.

A challenge asks the client for the Authorization header, while this auth reads credentials that need CSRF protection instead.

dmr.security.csrf.CSRF_SCHEME_NAME: Final = 'csrf'#

Default security scheme name for CSRF.

dmr.security.csrf.CSRF_HEADER_SCHEME_NAME: Final = 'csrf_header'#

Default security scheme name for the CSRF header (cookie mode only).

Semantic schema#

class dmr.semantic_schema.SecurityProvider[source]#

Provides security schemes and security requirements.

Added in version 0.16.0.

abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → list[SecurityRequirement][source]#

Provides a security schema usage requirement.

abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) → dict[str, SecurityScheme | Reference][source]#

Provides a security schema definition.

class dmr.semantic_schema.ResponseValidationSpecProvider(*, status_code: HTTPStatus = HTTPStatus.UNPROCESSABLE_ENTITY, description: str | Promise | None = 'Raised when returned response does not match the response schema')[source]#

Provide response specs for response schema validation.

Does not add itself for endpoints that have validate_responses turned off.

Should be added to dmr.settings.Settings.semantic_schema_providers setting.

status_code#

Status code to be returned when validation error happens.

Type:

http.HTTPStatus

description#

Response spec description for humans.

Type:

str | django.utils.functional.Promise | None

Added in version 0.16.0.

provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) → list[ResponseSpec][source]#

Provides responses that can happen when returning invalid data.

class dmr.semantic_schema.SecurityRequirementMerger[source]#

Interface for things that can merge security requirements.

What can do that?

  • security_merger merges user provided security requirements with the ones generated from auth

  • Semantic schema providers merge their own requirements with the ones generated from auth, like CSRFSemanticSchemaProvider does

Added in version 0.16.0.

abstractmethod merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[SecurityRequirement], auth_requirements: list[SecurityRequirement]) → list[SecurityRequirement][source]#

Merge own security requirements into the auth requirements.

This can implement both OR and AND logic depending on the security logic: several alternative requirements mean OR, several schemes in a single requirement mean AND.

Parameters:
  • metadata – Metadata of the endpoint that is being generated.

  • controller_cls – Controller class of this endpoint.

  • own_requirements – Requirements of the thing that merges, for example, user provided security.

  • auth_requirements – Requirements generated from auth, already processed by semantic schema providers.

Returns:

The final list of security requirements for the operation.

class dmr.semantic_schema.OrSecurityRequirementMerger[source]#

Merge security requirements as alternatives.

All requirements are used as-is, own requirements are added after the auth ones. A client can satisfy any of them, this is what OR means in OpenAPI.

This is the default value of security_merger.

Raises:

EndpointMetadataError – When the same requirement is present more than once in the result. It usually means that security repeats what auth already documents.

Added in version 0.16.0.

merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[SecurityRequirement], auth_requirements: list[SecurityRequirement]) → list[SecurityRequirement][source]#

Add own requirements as alternatives to the auth ones.