16.2.1.12. Policy Module

Base function to handle the policy entries in the database. This module only depends on the db/models.py

The functions of this module are tested in tests/test_lib_policy.py

A policy has the attributes

  • name

  • scope

  • action

  • realm

  • resolver

  • user

  • client

  • active

name is the unique identifier of a policy. scope is the area, where this policy is meant for. This can be values like admin, selfservice, authentication… scope takes only one value.

active is bool and indicates, whether a policy is active or not.

action, realm, resolver, user and client can take a comma separated list of values.

16.2.1.12.1. realm and resolver

If these are empty ‘*’, this policy matches each requested realm.

16.2.1.12.2. user

If the user is empty or ‘*’, this policy matches each user. You can exclude users from matching this policy, by prepending a ‘-’ or a ‘!’. *, -admin will match for all users except the admin.

You can also use regular expressions to match the user like customer_.* to match any user, starting with customer_.

Note

Regular expression will only work for exact matches. user1234 will not match user1 but only user1…

16.2.1.12.3. client

The client is identified by its IP address. A policy can contain a list of IP addresses or subnets. You can exclude clients from subnets by prepending the client with a ‘-’ or a ‘!’. 172.16.0.0/24, -172.16.0.17 will match each client in the subnet except the 172.16.0.17.

16.2.1.12.4. time

You can specify a time in which the policy should be active. Time formats are:

<dow>-<dow>:<hh>:<mm>-<hh>:<mm>, ...
<dow>:<hh>:<mm>-<hh>:<mm>
<dow>:<hh>-<hh>

and any combination of it. dow being day of week Mon, Tue, Wed, Thu, Fri, Sat, Sun.

class privacyidea.lib.policy.ACTIONVALUE[source]

This is a list of usual action values for e.g. policy action-values like otppin.

DISABLE = 'disable'
NONE = 'none'
TOKENPIN = 'tokenpin'
USERSTORE = 'userstore'
class privacyidea.lib.policy.AUTHORIZED[source]
ALLOW = 'grant_access'
DENY = 'deny_access'
class privacyidea.lib.policy.AUTOASSIGNVALUE[source]

This is the possible values for autoassign

NONE = 'any_pin'
USERSTORE = 'userstore'
class privacyidea.lib.policy.GROUP[source]

These are the allowed policy action groups. The policies will be grouped in the UI.

CONDITIONS = 'conditions'
CONTAINER = 'container'
ENROLLMENT = 'enrollment'
GENERAL = 'general'
MACHINE = 'machine'
MODIFYING_RESPONSE = 'modifying response'
PIN = 'pin'
REGISTRATION = 'registration and synchronization'
SERVICEID = 'service ID'
SETTING_ACTIONS = 'setting actions'
SMARTPHONE = 'smartphone'
SYSTEM = 'system'
TOKEN = 'token'
TOKENGROUP = 'tokengroup'
TOOLS = 'tools'
USER = 'user'
WIZARD = 'wizard'
class privacyidea.lib.policy.LOGINMODE[source]

This is the list of possible values for the login mode.

DISABLE = 'disable'
PRIVACYIDEA = 'privacyIDEA'
USERSTORE = 'userstore'
class privacyidea.lib.policy.MAIN_MENU[source]

These are the allowed top level menu items. These are used to toggle the visibility of the menu items depending on the rights of the user

AUDIT = 'audit'
COMPONENTS = 'components'
CONFIG = 'config'
MACHINES = 'machines'
TOKENS = 'tokens'
USERS = 'users'
class privacyidea.lib.policy.Match(g, **kwargs)[source]

This class provides a high-level API for policy matching.

It should not be instantiated directly. Instead, code should use one of the provided classmethods to construct a Match object. See the respective classmethods for details.

A Match object encapsulates a policy matching operation, i.e. a call to privacyidea.lib.policy.PolicyClass.match_policies(). In order to retrieve the matching policies, one should use one of policies(), action_values() and any(). By default, these functions write the matched policies to the audit log. This behavior can be explicitly disabled.

Every classmethod expects a so-called “context object” as its first argument. The context object implements the following attributes:

  • audit_object: an Audit object which is used to write the used

    policies to the audit log. In case False is passed for write_to_audit_log, the audit object may be None.

  • policy_object: a PolicyClass object that is used to retrieve the

    matching policies.

  • client_ip: the IP of the current client, as a string

  • logged_in_user: a dictionary with keys “username”, “realm”, “role”

    that describes the currently logged-in (managing) user

In our case, this context object is usually the flask.g object.

classmethod action_only(g, scope, action)[source]

Match active policies solely based on a scope and an action, which may also be None. The client IP is matched implicitly.

Parameters:
  • g – context object

  • scope – the policy scope. SCOPE.ADMIN cannot be passed, admin must be used instead.

  • action – the policy action, or None

Return type:

Match

action_values(unique, allow_white_space_in_action=False, write_to_audit_log=True)[source]

Return a dictionary of action values extracted from the matching policies.

The dictionary maps each action value to a list of policies which define this action value.

Parameters:
Return type:

dict

classmethod admin(g, action: str, user_obj: User = None, serial: str = None, container_serial: str = None) Match[source]

Match admin policies with an action and, optionally, a realm. Assumes that the currently logged-in user is an admin, and throws an error otherwise. Policies will be matched against the admin’s username and adminrealm, and optionally also the provided user_obj on which the admin is acting The client IP is matched implicitly.

Parameters:
  • g – context object

  • action – the policy action

  • user_obj (User or None) – the user against which policies should be matched. Can be None.

  • serial – The serial of a token from the request

  • container_serial – The serial of a container from the request data.

Return type:

Match

classmethod admin_or_user(g, action, user_obj, additional_realms=None, container_serial: str = None)[source]

Depending on the role of the currently logged-in user, match either scope=ADMIN or scope=USER policies. If the currently logged-in user is an admin, match policies against the username, adminrealm, the allowed user realms (if any) for the admin and the given user_obj on which the admin is acting. If the currently logged-in user is a user, match policies against the username and the given realm. The client IP is matched implicitly.

Parameters:
  • g – context object

  • action – the policy action

  • user_obj – the user_obj on which the administrator is acting

  • additional_realms – list of realms where at least one has to match the policy condition to be applied

  • container_serial – The serial of a container from the request data (used to check extended policy conditions).

Return type:

Match

allowed(write_to_audit_log=True)[source]

Determine if the matched action is allowed in the scope admin or user.

This is the case
  • either if there are no active policies defined in the matched scope

  • or the action is explicitly allowed by a policy in the matched scope

Example usage:

is_allowed = Match.user(g, scope=SCOPE.USER, action=ACTION.ENROLLPIN, user=user_object).allowed()
# is_allowed is now true
#  either if there is no active policy defined with scope=SCOPE.USER at all
#  or if there is a policy matching the given scope, action, user and client IP.
Parameters:

write_to_audit_log – If True, write the list of matching policies to the audit log

Returns:

True or False

any(write_to_audit_log=True)[source]

Return True if at least one policy matches.

Parameters:

write_to_audit_log – If True, write the list of matching policies to the audit log

Returns:

True or False

classmethod generic(g, scope: str = None, realm: str = None, resolver: str = None, user: str = None, user_object: User = None, client: str = None, action: str = None, adminrealm: str = None, adminuser: str = None, time: datetime = None, active: bool = True, sort_by_priority: bool = True, serial: str = None, extended_condition_check: list[str] | int | None = None, additional_realms: list = None, container_serial: str = None) Match[source]

Low-level legacy policy matching interface: Search for active policies and return them sorted by priority. All parameters that should be used for matching have to be passed explicitly. The client IP has to be passed explicitly. See privacyidea.lib.policy.PolicyClass.match_policies() for details.

Return type:

Match

policies(write_to_audit_log=True)[source]

Return a list of policies. The list is sorted by priority, which means that prioritized policies appear first.

Parameters:

write_to_audit_log – If True, write the list of matching policies to the audit log

Returns:

a list of policy dictionaries

Return type:

list

classmethod realm(g, scope, action, realm)[source]

Match active policies with a scope, an action and a user realm. The client IP is matched implicitly.

Parameters:
  • g – context object

  • scope – the policy scope. SCOPE.ADMIN cannot be passed, admin must be used instead.

  • action – the policy action

  • realm – the realm to match

Return type:

Match

classmethod token(g, scope, action, token_obj)[source]

Match active policies with a scope, an action and a token object. The client IP is matched implicitly. From the token object we try to determine the user as the owner. If the token has no owner, we try to determine the tokenrealm. We fall back to realm=None

Parameters:
  • g – context object

  • scope – the policy scope. SCOPE.ADMIN cannot be passed, admin must be used instead.

  • action – the policy action

  • token_obj – The token where the user object or the realm should match.

Return type:

Match

classmethod user(g, scope, action, user_object)[source]

Match active policies with a scope, an action and a user object (which may be None). The client IP is matched implicitly.

Parameters:
  • g – context object

  • scope – the policy scope. SCOPE.ADMIN cannot be passed, admin must be used instead.

  • action – the policy action

  • user_object (User or None) – the user object to match. Might also be None, which means that the policy attributes user, realm and resolver are ignored.

Return type:

Match

exception privacyidea.lib.policy.MatchingError(description='server error!', id=903)[source]
class privacyidea.lib.policy.PolicyClass[source]

A policy object can be used to query the current set of policies. The policy object itself does not store any policies. Instead, every query uses get_config_object to retrieve the request-local config object which contains the current set of policies.

Hence, reloading the request-local config object also reloads the set of policies.

static check_for_conflicts(policies, action)[source]

Given a (not necessarily sorted) list of policy dictionaries and an action name, check that there are no action value conflicts.

This raises a PolicyError if there are multiple policies with the highest priority which define different values for action.

Otherwise, the function just returns nothing.

Parameters:
  • policies – list of dictionaries

  • action – string

static extract_action_values(policies, action, unique=False, allow_white_space_in_action=False)[source]

Given an action, extract all values the given policies specify for that action.

Parameters:
  • policies (list) – a list of policy dictionaries

  • action (action) – a policy action

  • unique (bool) – if True, only consider the policy with the highest priority and check for policy conflicts (in this case, raise a PolicyError).

  • allow_white_space_in_action – Some policies like emailtext would allow entering text with whitespaces. These whitespaces must not be used to separate action values!

Returns:

a dictionary mapping action values to lists of matching policies.

filter_policies_by_conditions(policies: list[dict], user_object: User | None = None, request_headers: EnvironHeaders | None = None, serial: str | None = None, extended_condition_check: None | int | list[str] = None, container_serial: str | None = None, request_data: dict | None = None) list[dict][source]

Evaluates for each policy condition if it matches the actual request (user / token / request headers) and returns a list of all matching policies. Raises a PolicyError if any condition misconfiguration (unknown comparator or section) occurs and depending on the condition definition also if some required data is missing.

Parameters:
  • policies – a list of policy dictionaries

  • user_object – a User object, or None if there is no current user

  • request_headers – The HTTP headers

  • serial – The serial of a token or None if not contained in the request data

  • extended_condition_check – One of CONDITION_CHECK (1 - not check, list of sections to check, None - check all).

  • container_serial – The serial of a container or None if not contained in the request data

  • request_data – The request data as dictionary, if available

Returns:

a list of matching policy dictionaries

get_action_values(action: str, scope: str = 'authorization', realm: str | None = None, resolver: str | None = None, user: str | None = None, client: str | None = None, unique: bool = False, allow_white_space_in_action: bool = False, adminrealm: str | None = None, adminuser: str | None = None, user_object: User | None = None, audit_data=None, user_agent: str | None = None)[source]

Get the defined action values for a certain actions.

Calling the function with parameters like:

scope: authorization
action: tokentype

would return a dictionary of {tokentype: policyname}.

A call with the parameters:

scope: authorization
action: serial

would return a dictionary of {serial: policyname}

All parameters not described below are covered in the documentation of match_policies.

Parameters:
  • unique – if set, the function will only consider the policy with the highest priority and check for policy conflicts.

  • allow_white_space_in_action (bool) – Some policies like emailtext would allow entering text with whitespaces. These whitespaces must not be used to separate action values!

  • audit_data – This is a dictionary, that can take audit_data in the g object. If set, this dictionary will be filled with the list of triggered policynames in the key “policies”. This can be useful for policies like ACTION.OTPPIN - where it is clear, that the found policy will be used. It could make less sense with an action like ACTION.LASTAUTH - where the value of the action needs to be evaluated in a more special case.

  • user_agent – The user agent of the request

Return type:

dict

static get_policy_condition_from_tuple(condition_tuple: tuple, policy_name: str, pass_if_inactive: bool = False) PolicyConditionClass[source]

Converts the condition tuple into a PolicyConditionClass object.

Parameters:
  • condition_tuple – A tuple of 5 or 6 values (section, key, comparator, value, active, handle_missing_data)

  • policy_name – The name of the policy (used for the error message)

  • pass_if_inactive – If True, no error is raised for invalid parameters if the condition is inactive

Returns:

A PolicyConditionClass object

list_policies(name: str | None = None, scope: str | None = None, realm: str | None = None, active: bool | None = None, resolver: str | None = None, user: str | None = None, client: str | None = None, action: str | None = None, pinode: str | None = None, adminrealm: str | None = None, adminuser: str | None = None, sort_by_priority: bool = True, additional_realms: list | None = None, user_agent: str | None = None) list[dict][source]

Return the policies, filtered by the given values.

The following rule holds for all filter arguments:

If None is passed as a value, policies are not filtered according to the argument at all. As an example, if realm=None is passed, policies are matched regardless of their realm attribute. If any value is passed (even the empty string), policies are filtered according to the given value. As an example, if realm='' is passed, only policies that have a matching (or empty) realm attribute are returned.

The only exception is the client parameter, which does not accept the empty string, and throws a ParameterError if the empty string is passed.

If additional_realms are passed as well as a user, all policies applicable to a realm of the additional_realms list or applicable to the user realm combination are returned. The user is only matched in combination with the realm parameter and not with the additional realms.

Parameters:
  • name – The name of the policy

  • scope – The scope of the policy

  • realm – The realm of a user in the policy

  • active – One of None, True, False: All policies, only active or only inactive policies

  • resolver – Only policies with this resolver

  • pinode – Only policies with this privacyIDEA node

  • user – Only policies with this user

  • client

  • action – Only policies, that contain this very action.

  • adminrealm – This is the realm of the admin. This is only evaluated in the scope admin.

  • adminuser – This is the username of the admin. This in only evaluated in the scope admin.

  • additional_realms – A list of realms that should be additionally checked besides the user realm combination

  • sort_by_priority – If true, sort the resulting list by priority, ascending by their policy numbers.

  • user_agent – The user agent of the request

Returns:

list of policies

Return type:

list of dicts

match_policies(name: str | None = None, scope: str | None = None, realm: str | None = None, active: bool | None = None, resolver: str | None = None, user: str | None = None, user_object: User | None = None, pinode: str | None = None, client: str | None = None, action: str | None = None, adminrealm: str | None = None, adminuser: str | None = None, time: datetime | None = None, sort_by_priority: bool = True, audit_data: dict | None = None, request_headers: EnvironHeaders | None = None, serial: str | None = None, extended_condition_check: int | list[str] | None = None, additional_realms: list | None = None, container_serial: str | None = None, request_data: dict | None = None, user_agent: str | None = None) list[dict][source]

Return all policies matching the given context. Optionally, write the matching policies to the audit log.

In order to retrieve policies matching the current user, callers can either pass a user(name), resolver and realm, or pass a user object from which login name, resolver and realm will be read. In case of conflicting parameters, a ParameterError will be raised.

This function takes all parameters taken by list_policies, plus some additional parameters.

Parameters:
  • name – see list_policies

  • scope – see list_policies

  • realm – see list_policies

  • active – see list_policies

  • resolver – see list_policies

  • user – the user name

  • user_object – the currently active user, or None

  • pinode – the privacyIDEA node name

  • client – see list_policies

  • action – see list_policies

  • adminrealm – see list_policies

  • adminuser – see list_policies

  • time (datetime or None) – return only policies that are valid at the specified time. Defaults to the current time.

  • sort_by_priority

  • audit_data – A dictionary with audit data collected during a request. This method will add found policies to the dictionary.

  • request_headers – A dict with HTTP headers

  • serial – The serial number of the token

  • extended_condition_check – One of ConditionCheck (1 - no condition check, None - check all conditions) or a list of conditions to check for the policies

  • additional_realms – A list of realms that should be additionally checked besides the user realm combination

  • container_serial – The container serial from the request if available

  • request_data – The request data as dictionary

  • user_agent – The user agent of the request

Returns:

a list of policy dictionaries

property policies

Shorthand to retrieve the set of policies of the request-local config object

ui_get_enroll_tokentypes(client: str, logged_in_user: dict, user_agent: str | None = None)[source]

Return a dictionary of the allowed tokentypes for the logged in user. This used for the token enrollment UI.

It looks like this:

{“hotp”: “HOTP: event based One Time Passwords”,

“totp”: “TOTP: time based One Time Passwords”, “spass”: “SPass: Simple Pass token. Static passwords”, “motp”: “mOTP: classical mobile One Time Passwords”, “sshkey”: “SSH Public Key: The public SSH key”, “yubikey”: “Yubikey AES mode: One Time Passwords with Yubikey”, “remote”: “Remote Token: Forward authentication request to another server”, “yubico”: “Yubikey Cloud mode: Forward authentication request to YubiCloud”, “radius”: “RADIUS: Forward authentication request to a RADIUS server”, “email”: “EMail: Send a One Time Passwort to the users email address”, “sms”: “SMS: Send a One Time Password to the users mobile phone”, “certificate”: “Certificate: Enroll an x509 Certificate Token.”}

Parameters:
  • client (basestring) – Client IP address

  • logged_in_user (dict) – The Dict of the logged in user

  • user_agent – The user agent of the request

Returns:

list of token types, the user may enroll

ui_get_main_menus(logged_in_user: dict, client: str | None = None, user_agent: str | None = None) list[source]

Get the list of allowed main menus derived from the policies for the given user - admin or normal user. It fetches all policies for this user and compiles a list of allowed menus to display or hide in the UI.

Parameters:
  • logged_in_user – The logged in user, a dictionary with keys “username”, “realm” and “role”.

  • client – The IP address of the client

  • user_agent – The user agent of the request

Returns:

A list of MENUs to be displayed

ui_get_rights(scope: str, realm: str, username: str, client: str | None = None, user_agent: str | None = None)[source]

Get the rights derived from the policies for the given realm and user. Works for admins and normal users. It fetches all policies for this user and compiles a maximum list of allowed rights, that can be used to hide certain UI elements.

Parameters:
  • scope – Can be SCOPE.ADMIN or SCOPE.USER

  • realm – Is either user users realm or the adminrealm

  • username – The loginname of the user

  • client – The HTTP client IP

  • user_agent – The user agent of the request

Returns:

A list of actions

class privacyidea.lib.policy.REMOTE_USER[source]

The list of possible values for the remote_user policy.

ACTIVE = 'allowed'
DISABLE = 'disable'
FORCE = 'force'
class privacyidea.lib.policy.SCOPE[source]

This is the list of the allowed scopes that can be used in policy definitions.

ADMIN = 'admin'
AUDIT = 'audit'
AUTH = 'authentication'
AUTHZ = 'authorization'
CONTAINER = 'container'
ENROLL = 'enrollment'
REGISTER = 'register'
TOKEN = 'token'
USER = 'user'
WEBUI = 'webui'
classmethod get_all_scopes() list[str][source]

Return all valid scopes as a list

class privacyidea.lib.policy.TIMEOUT_ACTION[source]

This is a list of actions values for idle users

LOCKSCREEN = 'lockscreen'
LOGOUT = 'logout'
class privacyidea.lib.policy.TYPE[source]
BOOL = 'bool'
INT = 'int'
STRING = 'str'
privacyidea.lib.policy.check_pin(g, pin, tokentype, user_obj)[source]

get the policies for minimum length, maximum length and PIN contents first try to get a token specific policy - otherwise fall back to default policy.

Raises an exception, if the PIN does not comply to the policies.

Parameters:
  • g

  • pin

  • tokentype

  • user_obj

privacyidea.lib.policy.convert_action_dict_to_python_dict(action: str) dict[str, str][source]

Policy actions can not contain commas. Hence, the format ‘key1’:’value2’-‘key2’:’value2’ is used. This function takes such a string as input and converts it into a dictionary.

Parameters:

action – Action value of a policy

Returns:

Action value formatted as python dictionary

privacyidea.lib.policy.delete_all_policies()[source]
privacyidea.lib.policy.delete_policies(names)[source]

Delete multiple policies. ResourceNotFoundErrors are suppressed.

Parameters:

names – the names of the policies to be deleted

Returns:

the IDs of the deleted policies

Return type:

list[int]

privacyidea.lib.policy.delete_policy(name)[source]

Function to delete one named policy. Raise ResourceNotFoundError if there is no such policy.

Parameters:

name – the name of the policy to be deleted

Returns:

the ID of the deleted policy

Return type:

int

privacyidea.lib.policy.enable_policy(name, enable=True)[source]

Enable or disable the policy with the given name.

Parameters:
  • name (str) – Name of the policy

  • enable (bool) – Set to True to enable the policy

Returns:

ID of the policy

Return type:

int

privacyidea.lib.policy.export_policies(policies)[source]

This function takes a policy list and creates an export file from it

Parameters:

policies (list of policy dictionaries) – a policy definition

Returns:

the contents of the file

Return type:

string

privacyidea.lib.policy.export_policy(name=None)[source]

Export given or all policy configuration

privacyidea.lib.policy.get_action_values_from_options(scope, action, options)[source]

This function is used in the library level to fetch policy action values from a given option dictionary.

The matched policies are not written to the audit log.

Returns:

A scalar, string or None

privacyidea.lib.policy.get_allowed_custom_attributes(g, user_obj)[source]

Return the list off allowed custom user attributes that can be set and deleted. Returns a dictionary with the two keys “delete” and “set.

Parameters:
  • g

  • user_obj – The User object to check the allowed attributes for

Returns:

dict

privacyidea.lib.policy.get_policies(active: bool | None = None, name: str | None = None, scope: str | None = None, action: str | None = None, realm: str | None = None, admin_realm: str | None = None, admin_user: str | None = None, resolver: str | None = None, pi_node: str | None = None, user: str | None = None, client: str | None = None, time: str | None = None, priority: int | None = None, user_agent: str | None = None) list[dict][source]

Get all policies from the database, optionally filtered by the given parameters.

Parameters:
  • active – If the policy is active or not

  • name – The name of the policy

  • scope – The scope of the policy

  • action – A scope specific action or a comma separated list of actions

  • realm – A realm, for which this policy is valid

  • admin_realm – The name of the realm of administrators

  • admin_user – A comma separated list of administrator user names

  • resolver – A resolver, for which this policy is valid

  • pi_node – A privacyIDEA node or a list of privacyIDEA node names

  • user – A username or a list of usernames

  • client – A client for which this policy is valid

  • time – A time frame when the policy is valid, e.g. “Mon-Fri: 8-16”

  • priority – The priority of the policy

  • user_agent – A list of user agents for which this policy is valid

Returns:

A list of all policies as dictionaries

privacyidea.lib.policy.get_policy_condition_comparators()[source]
Returns:

a dictionary mapping comparators to dictionaries with the following keys: * "description", a human-readable description of the comparator

privacyidea.lib.policy.get_policy_condition_sections()[source]
Returns:

a dictionary mapping condition sections to dictionaries with the following keys: * "description", a human-readable description of the section

privacyidea.lib.policy.get_static_policy_definitions(scope=None)[source]

These are the static hard coded policy definitions. They can be enhanced by token based policy definitions, that can be found in lib.token.get_dynamic_policy_definitions.

Parameters:

scope (basestring) – Optional the scope of the policies

Returns:

allowed scopes with allowed actions, the type of action and a description.

Return type:

dict

privacyidea.lib.policy.import_policies(file_contents)[source]

This function imports policies from a file.

The file has a config_object format, i.e. the text file has a header:

[<policy_name>]
key = value

and key value pairs.

Parameters:

file_contents (basestring) – The contents of the file

Returns:

number of imported policies

Return type:

int

privacyidea.lib.policy.import_policy(data, name=None)[source]

Import policy configuration

privacyidea.lib.policy.remove_wildcards_and_negations(value_list: list[str]) list[str][source]

Removes leading negation characters (“!” or “-”) from the strings in a list. Removes wildcard (“*”) and empty strings from the list.

Parameters:

value_list – A list of values to be processed

Returns:

A list of values without leading negation characters and wildcards

privacyidea.lib.policy.rename_policy(name: str, new_name: str) int[source]

Rename a policy and invalidate the config object so that policies are reloaded.

Parameters:
  • name – The name of the policy to be renamed

  • new_name – The new name of the policy

Returns:

The database ID of the renamed policy

privacyidea.lib.policy.set_policy(name: str | None = None, scope: str | None = None, action: str | list | None = None, realm: str | list | None = None, resolver: str | list | None = None, user: str | list | None = None, time: str | None = None, client: str | None = None, active: bool = True, adminrealm: str | list | None = None, adminuser: str | list | None = None, priority: int | str | None = None, check_all_resolvers: bool = False, conditions: list | None = None, pinode: str | list | None = None, description: str | None = None, user_case_insensitive: bool = False, user_agents: str | list[str] | None = None) int[source]

Function to set a policy.

If the policy with this name already exists, it updates the policy. It expects a dict of with the following keys:

Parameters:
  • name – The name of the policy

  • scope – The scope of the policy. Something like “admin” or “authentication”

  • action – A scope specific action or a comma separated list of actions

  • realm – A realm, for which this policy is valid

  • resolver – A resolver, for which this policy is valid

  • user – A username or a list of usernames

  • time – N/A if type()

  • client – A client IP with optionally a subnet like 172.16.0.0/16

  • active (bool) – If the policy is active or not

  • adminrealm (str) – The name of the realm of administrators

  • adminuser (str) – A comma separated list of administrators

  • priority (int) – the priority of the policy (smaller values having higher priority)

  • check_all_resolvers (bool) – If all the resolvers of a user should be checked with this policy

  • user_case_insensitive (bool) – The username should be case-insensitive.

  • conditions – A list of 5- or 6-tuples (section, key, comparator, value, active, handle_missing_data) of policy conditions

  • pinode – A privacyIDEA node or a list of privacyIDEA nodes.

  • description (str) – A description for the policy

  • user_agents – A list of user agents for which this policy is valid.

Returns:

The database ID of the policy

privacyidea.lib.policy.set_policy_conditions(conditions: list[PolicyConditionClass], policy: Policy)[source]

This function writes the policy conditions to the database. Old conditions are removed. It does not commit the database session as we assume that the calling function is also doing some database operations and will do a single final commit. It raises a ParameterError if the conditions are not valid.

Parameters:
  • conditions – A list of policy conditions

  • policy – The policy to which the conditions belong

privacyidea.lib.policy.validate_actions(scope: str, action: str | dict) bool[source]

Check if the given actions are valid for the given scope.

Parameters:
  • scope – The scope of the policy

  • action – The policy actions

Returns:

True if all actions are valid, raises a Parameter Error otherwise

privacyidea.lib.policy.validate_values(values: str | list | None, allowed_values: list, name: str) bool[source]

Checks if all values are contained in the ‘allowed_values’ list.

Parameters:
  • values – Values to be evaluated whether they are defined. Either passed as list of strings or as a comma separated list as single string

  • allowed_values – A list of allowed values

  • name – The name of the parameter used for an error message

Returns:

True if all values are valid, raise a ParameterError otherwise