Settings
- class nginx_ldap_auth.settings.Settings(_case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | None = None, _secrets_dir: PathType | None = None, *, debug: bool = False, loglevel: Literal['NOTSET', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'] = 'INFO', log_type: Literal['json', 'text'] = 'text', auth_realm: str = 'Restricted', insecure: bool = False, cookie_name: str = 'nginxauth', cookie_domain: str | None = None, secret_key: str, session_max_age: int = 0, use_rolling_session: bool = False, session_backend: Literal['redis', 'memory'] = 'memory', redis_url: RedisDsn | None = None, redis_prefix: str = 'nginx_ldap_auth.', ldap_uri: str, ldap_binddn: str, ldap_password: str, ldap_starttls: bool = True, ldap_validate_cert: bool = True, ldap_ca_cert_name: str | None = None, ldap_ca_cert_dir: Path | None = None, ldap_disable_referrals: bool = False, ldap_basedn: str, ldap_user_basedn: str | None = None, ldap_username_attribute: str = 'uid', ldap_full_name_attribute: str = 'cn', ldap_get_user_filter: str = '{username_attribute}={username}', ldap_authorization_filter: str | None = None, allow_authorization_filter_header: bool = True, ldap_timeout: int = 15, ldap_min_pool_size: int = 1, ldap_max_pool_size: int = 30, ldap_pool_connection_lifetime_seconds: int = 20, duo_enabled: bool = False, duo_host: str | None = None, duo_ikey: str | None = None, duo_skey: str | None = None, sentry_url: str | None = None)[source]
Settings for the nginx_ldap_auth service.
- loglevel: Literal['NOTSET', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']
Default log level. Choose from any of the standard Python log levels.
- auth_realm: str
Use this as the title for the login form, to give a hint to the user as to what they’re logging into
- use_rolling_session: bool
Reset the session lifetime to
session_max_ageevery time the user accesses the protected site
- redis_url: RedisDsn | None
If using the Redis session backend, the DSN on which to connect to Redis.
A fully specified Redis DSN looks like this:
redis://[username][:password]@host:port/db
The username is only necessary if you are using role-based access controls on your Redis server. Otherwise the password is sufficient if you have a server password for your Redis server.
If you don’t specify a database,
0is used.If you don’t specify a password, no password is used.
If you don’t specify a port,
6379is used.
- ldap_ca_cert_name: str | None
The path to the CA certificate to use when validating the LDAP certificate
- ldap_ca_cert_dir: Path | None
The path to the CA certificate directory to use when validating the LDAP certificate
- ldap_user_basedn: str | None
The base DN to append to the user’s username when binding. This is only important for Active Directory, where we need to use the value of
userPrincipalName(typically the user’s email address) as the username intead of the dn which would be built assAMAccountName=user,{LDAP_BASEDN}. Include the@at the begining of the string. If this is set, the binddn will be{username}{ldap_user_basedn}
- ldap_full_name_attribute: str
The LDAP attribute to use as the full name when getting search results
- ldap_get_user_filter: str
The LDAP search filter to use when searching for a user. This should be a valid LDAP search filter. The search will be a SUBTREE search with the base DN of
ldap_basedn.You may use these replacement fields in the filter:
{username_attribute}: the value ofSettings.ldap_username_attribute{username_full_name_attribute}: the value ofSettings.ldap_full_name_attribute
The
{username}placeholder must be present in the filter, as it is used in the search filter as the placeholder for the username supplied by the user from the login form.
- ldap_authorization_filter: str | None
The LDAP search filter to use to determine whether a user is authorized. This should a valid LDAP search filter. If this is
None, all users who can successfully authenticate will be authorized. If this is notNone, the search with this filter must return at least one result for the user to be authorized.You may use these replacement fields in the filter:
{username_attribute}: the value ofldap_username_attribute{username_full_name_attribute}: the value ofldap_full_name_attribute
The
{username}placeholder must be present in the filter, as it is used in the search filter as the placeholder for the username supplied by the user from the login form.
- allow_authorization_filter_header: bool
Whether to allow the
X-Authorization-Filterheader to overrideldap_authorization_filter. When set toTrue(the default), the header value takes precedence over the environment variable setting.Warning
Setting this to
Truewithout properly configuring NGINX to control theX-Authorization-Filterheader is a security risk. Malicious clients could send a permissive filter (e.g.,(objectClass=*)) to bypass group-based authorization restrictions.For secure deployments, set this to
Falseand use only theLDAP_AUTHORIZATION_FILTERenvironment variable, or ensure your NGINX configuration explicitly sets or clears the header usingproxy_set_headerbefore forwarding requests.Note
The default is
Truefor backwards compatibility. Future versions may change the default toFalsefor improved security.
- sentry_url: str | None
The sentry DSN to use for error reporting. If this is
None, no error reporting will be done.
- model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'extra': 'forbid', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_file': None, 'yaml_file_encoding': None}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- redis_url_required_if_session_type_is_redis()[source]
If we’ve configured the session backend to be
redis,redis_urlis required.- Raises:
ValidationError –
redis_urlis required ifsession_backendisredis –
- duo_settings_required_if_enabled()[source]
If we’ve enabled Duo MFA,
duo_host,duo_ikey, andduo_skeyare required.- Raises:
ValidationError – Duo settings are required if
duo_enabledisTrue –
- ensure_authorization_filter_header_is_a_valid_ldap_filter()[source]
Ensure that the authorization filter is a valid LDAP filter.
- Raises:
ValueError – The authorization filter is not a valid LDAP filter
ValueError – The authorization filter does not use the {username} placeholder
- ensure_get_user_filter_is_a_valid_ldap_filter()[source]
Ensure that the get user filter is a valid LDAP filter.
- Raises:
ValueError – The get user filter is not a valid LDAP filter
ValueError – The get user filter does not use the {username} placeholder
- ensure_ca_cert_cert()[source]
Ensure that the CA certificate path is valid.
If ldap_ca_cert_name is set, ldap_ca_cert_dir must be set
If ldap_ca_cert_dir is set, ldap_ca_cert_name must be set
ldap_ca_cert_dir must exist and be a directory
ldap_ca_cert_name must exist in ldap_ca_cert_dir and be a file
- Raises:
ValueError – ldap_ca_cert_dir does not exist
ValueError – ldap_ca_cert_dir is not a directory
ValueError – ldap_ca_cert_name does not exist in ldap_ca_cert_dir
ValueError – ldap_ca_cert_name is not a file
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- dict(*, include: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]
- json(*, include: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self
Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#model_copy
Returns a copy of the model.
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False) dict[str, Any]
Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, include: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: Set[int] | Set[str] | Mapping[int, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, Set[int] | Set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False) str
Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A JSON string representation of the model.
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- model_fields: ClassVar[dict[str, FieldInfo]] = {'allow_authorization_filter_header': FieldInfo(annotation=bool, required=False, default=True), 'auth_realm': FieldInfo(annotation=str, required=False, default='Restricted'), 'cookie_domain': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'cookie_name': FieldInfo(annotation=str, required=False, default='nginxauth'), 'debug': FieldInfo(annotation=bool, required=False, default=False), 'duo_enabled': FieldInfo(annotation=bool, required=False, default=False), 'duo_host': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'duo_ikey': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'duo_skey': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'insecure': FieldInfo(annotation=bool, required=False, default=False), 'ldap_authorization_filter': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'ldap_basedn': FieldInfo(annotation=str, required=True), 'ldap_binddn': FieldInfo(annotation=str, required=True), 'ldap_ca_cert_dir': FieldInfo(annotation=Union[Path, NoneType], required=False, default=None), 'ldap_ca_cert_name': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'ldap_disable_referrals': FieldInfo(annotation=bool, required=False, default=False), 'ldap_full_name_attribute': FieldInfo(annotation=str, required=False, default='cn'), 'ldap_get_user_filter': FieldInfo(annotation=str, required=False, default='{username_attribute}={username}'), 'ldap_max_pool_size': FieldInfo(annotation=int, required=False, default=30), 'ldap_min_pool_size': FieldInfo(annotation=int, required=False, default=1), 'ldap_password': FieldInfo(annotation=str, required=True), 'ldap_pool_connection_lifetime_seconds': FieldInfo(annotation=int, required=False, default=20), 'ldap_starttls': FieldInfo(annotation=bool, required=False, default=True), 'ldap_timeout': FieldInfo(annotation=int, required=False, default=15), 'ldap_uri': FieldInfo(annotation=str, required=True), 'ldap_user_basedn': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'ldap_username_attribute': FieldInfo(annotation=str, required=False, default='uid'), 'ldap_validate_cert': FieldInfo(annotation=bool, required=False, default=True), 'log_type': FieldInfo(annotation=Literal['json', 'text'], required=False, default='text'), 'loglevel': FieldInfo(annotation=Literal['NOTSET', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'], required=False, default='INFO'), 'redis_prefix': FieldInfo(annotation=str, required=False, default='nginx_ldap_auth.'), 'redis_url': FieldInfo(annotation=Union[RedisDsn, NoneType], required=False, default=None), 'secret_key': FieldInfo(annotation=str, required=True), 'sentry_url': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'session_backend': FieldInfo(annotation=Literal['redis', 'memory'], required=False, default='memory'), 'session_max_age': FieldInfo(annotation=int, required=False, default=0), 'use_rolling_session': FieldInfo(annotation=bool, required=False, default=False)}
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation') dict[str, Any]
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- model_post_init(_BaseModel__context: Any) None
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, from_attributes: bool | None = None, context: Any | None = None) Self
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, context: Any | None = None) Self
Usage docs: https://docs.pydantic.dev/2.10/concepts/json/#json-parsing
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
context – Extra variables to pass to the validator.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, context: Any | None = None) Self
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
context – Extra variables to pass to the validator.
- Returns:
The validated Pydantic model.
- classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
- classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self
- classmethod schema_json(*, by_alias: bool = True, ref_template: str = '#/$defs/{model}', **dumps_kwargs: Any) str
- classmethod settings_customise_sources(settings_cls: type[pydantic_settings.main.BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource) tuple[pydantic_settings.sources.PydanticBaseSettingsSource, ...]
Define the sources and their order for loading the settings values.
- Parameters:
settings_cls – The Settings class.
init_settings – The InitSettingsSource instance.
env_settings – The EnvSettingsSource instance.
dotenv_settings – The DotEnvSettingsSource instance.
file_secret_settings – The SecretsSettingsSource instance.
- Returns:
A tuple containing the sources and their order for loading the settings values.