17.2.1.5. Conditional Access Module¶
The conditional-access package classifies each authentication request, records the outcome in the authentication log and feeds it to the conditional-access engine. See Authentication Log for what an entry records and how it is searched.
17.2.1.5.1. Authentication event types¶
- privacyidea.lib.conditional_access.authentication_event_types.AUTH_EVENT_REASON_DETAIL_KEY = 'authentication_event_reason_detail'¶
Reply-dict key carrying the classified reason’s detail from the lib layer to the api layer.
- class privacyidea.lib.conditional_access.authentication_event_types.AuthEventOutcome(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Outcome class of an
AuthEventType: did the authenticationSUCCESS(succeed),FAILURE(fail/get denied), or is itPENDING(still in flight – a challenge was sent/continued/approved out of band, or an enrollment was triggered).This is a domain classification, not a presentation/severity choice: it lets callers group events by result – e.g. a conditional-access policy condition selecting all failed events, or the WebUI coloring a row – without enumerating each event type.
str/Enum(notStrEnum) for 3.10 compatibility, likeAuthEventType.- FAILURE = 'failure'¶
- PENDING = 'pending'¶
- SUCCESS = 'success'¶
- class privacyidea.lib.conditional_access.authentication_event_types.AuthEventReason(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Why an
AuthEventTypecame out the way it did.The event type answers what happened to a request; several distinct causes share one of them, and the cause is what an admin has to act on.
NO_USABLE_TOKENis the clearest case: it is the same event whether every token is disabled, past its failcount, outside its validity period or simply not yet enrolled, which are four different pieces of advice for the person reading the log. Recording the reasons separately keeps the event vocabulary small (a row is still classified by exactly one event) while making the log answer “why”.A reason is machine-readable and low-cardinality, so it can be filtered on like an event type. Anything specific to one request (which policy denied it, which serial failed for which reason) goes in the row’s
other_infoinstead; seeAUTH_EVENT_REASON_DETAIL_KEY.An entry carries every reason its request produced - a user’s tokens can fail differently within one request, and each of those is a separate piece of advice, filterable on its own. They are listed in the order declared below (see
order_request_reasons()), which is for determinism rather than importance: no reason outranks another, and none is dropped in favour of one. Not every event has one:LOGIN_SUCCESSneeds none, and a request nobody classified simply has an empty list, which is why the reasons are rows of their own and no code path is obliged to add any.The order the members are declared in therefore is the order they are recorded in: keep the groups below together when adding one.
str/Enum(notStrEnum) for Python 3.10, likeAuthEventType.- AUTHORIZATION_DENIED = 'AUTHORIZATION_DENIED'¶
- AUTH_MAX_FAIL = 'AUTH_MAX_FAIL'¶
- AUTH_MAX_SUCCESS = 'AUTH_MAX_SUCCESS'¶
- CHALLENGE_DECLINED_ON_DEVICE = 'CHALLENGE_DECLINED_ON_DEVICE'¶
- CHALLENGE_EXPIRED = 'CHALLENGE_EXPIRED'¶
- CHALLENGE_NOT_DELIVERED = 'CHALLENGE_NOT_DELIVERED'¶
- CHALLENGE_UNKNOWN_TRANSACTION = 'CHALLENGE_UNKNOWN_TRANSACTION'¶
- CHALLENGE_WRONG_RESPONSE = 'CHALLENGE_WRONG_RESPONSE'¶
- LAST_AUTH_TOO_OLD = 'LAST_AUTH_TOO_OLD'¶
- LOGIN_MODE_DISABLED = 'LOGIN_MODE_DISABLED'¶
- MACHINE_NOT_IDENTIFIED = 'MACHINE_NOT_IDENTIFIED'¶
- NOT_AN_OFFLINE_TOKEN = 'NOT_AN_OFFLINE_TOKEN'¶
- REFILLTOKEN_MISMATCH = 'REFILLTOKEN_MISMATCH'¶
- SERIAL_NOT_ALLOWED = 'SERIAL_NOT_ALLOWED'¶
- TOKENINFO_MISMATCH = 'TOKENINFO_MISMATCH'¶
- TOKENTYPE_NOT_ALLOWED = 'TOKENTYPE_NOT_ALLOWED'¶
- TOKEN_AUTH_COUNTER_EXCEEDED = 'TOKEN_AUTH_COUNTER_EXCEEDED'¶
- TOKEN_DISABLED = 'TOKEN_DISABLED'¶
- TOKEN_FAILCOUNT_EXCEEDED = 'TOKEN_FAILCOUNT_EXCEEDED'¶
- TOKEN_NOT_APPLICABLE = 'TOKEN_NOT_APPLICABLE'¶
- TOKEN_NOT_FIT_FOR_CHALLENGE = 'TOKEN_NOT_FIT_FOR_CHALLENGE'¶
- TOKEN_NOT_YET_ENROLLED = 'TOKEN_NOT_YET_ENROLLED'¶
- TOKEN_NO_CHALLENGE_MODE = 'TOKEN_NO_CHALLENGE_MODE'¶
- TOKEN_OUTSIDE_VALIDITY_PERIOD = 'TOKEN_OUTSIDE_VALIDITY_PERIOD'¶
- TOKEN_REVOKED = 'TOKEN_REVOKED'¶
- TOKEN_TYPE_DISABLED = 'TOKEN_TYPE_DISABLED'¶
- WEBUI_PASSKEY_LOGIN_DISABLED = 'WEBUI_PASSKEY_LOGIN_DISABLED'¶
- WRONG_OTP = 'WRONG_OTP'¶
- class privacyidea.lib.conditional_access.authentication_event_types.AuthEventType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Event types written to the authentication log.
stris used instead ofStrEnum(3.11+) for compatibility with Python 3.10. The__str__override normalizesstr()/f-string output to the value across all supported versions (3.10-3.14); without it the output would differ between versions.- ACCESS_DENIED = 'ACCESS_DENIED'¶
- CHALLENGE_ANSWERED_FAIL = 'CHALLENGE_ANSWERED_FAIL'¶
- CHALLENGE_ANSWERED_OUT_OF_BAND = 'CHALLENGE_ANSWERED_OUT_OF_BAND'¶
- CHALLENGE_CANCELLED = 'CHALLENGE_CANCELLED'¶
- CHALLENGE_CONTINUED = 'CHALLENGE_CONTINUED'¶
- CHALLENGE_DECLINED = 'CHALLENGE_DECLINED'¶
- CHALLENGE_DECLINED_UNKNOWN_TRIGGER = 'CHALLENGE_DECLINED_UNKNOWN_TRIGGER'¶
- CHALLENGE_TRIGGERED = 'CHALLENGE_TRIGGERED'¶
- CHALLENGE_TRIGGER_FAIL = 'CHALLENGE_TRIGGER_FAIL'¶
- DEVICE_TOKEN_REUSED = 'DEVICE_TOKEN_REUSED'¶
- ENROLLMENT_CANCELED_FAIL = 'ENROLLMENT_CANCELED_FAIL'¶
- ENROLLMENT_FAIL = 'ENROLLMENT_FAIL'¶
- ENROLLMENT_TRIGGERED = 'ENROLLMENT_TRIGGERED'¶
- INVALID_TOKEN_TYPE = 'INVALID_TOKEN_TYPE'¶
- IP_BLOCKED = 'IP_BLOCKED'¶
- LOGIN_NAME_NOT_UNIQUE = 'LOGIN_NAME_NOT_UNIQUE'¶
- LOGIN_SUCCESS = 'LOGIN_SUCCESS'¶
- MFA_FAIL = 'MFA_FAIL'¶
- NOT_AUTHORIZED = 'NOT_AUTHORIZED'¶
- NO_TOKEN = 'NO_TOKEN'¶
- NO_USABLE_TOKEN = 'NO_USABLE_TOKEN'¶
- OFFLINE_REFILL_FAIL = 'OFFLINE_REFILL_FAIL'¶
- OFFLINE_REFILL_SUCCESS = 'OFFLINE_REFILL_SUCCESS'¶
- PASSWORD_FAIL = 'PASSWORD_FAIL'¶
- PIN_FAIL = 'PIN_FAIL'¶
- POST_AUTHENTICATION_FAIL = 'POST_AUTHENTICATION_FAIL'¶
- SUSPENDED_API_KEY_USED = 'SUSPENDED_API_KEY_USED'¶
- TOKEN_ONLY_FAIL = 'TOKEN_ONLY_FAIL'¶
- UNKNOWN_FAIL_REASON = 'UNKNOWN_FAIL_REASON'¶
- USER_LOCKED = 'USER_LOCKED'¶
- USER_STORE_UNAVAILABLE = 'USER_STORE_UNAVAILABLE'¶
- USER_UNKNOWN = 'USER_UNKNOWN'¶
- class privacyidea.lib.conditional_access.authentication_event_types.AuthLogUserRole(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Role of the authenticating principal recorded in the authentication log. The two admin values are kept distinct because conditional-access rules may treat them differently:
admin-externaladmins come from an admin realm (an external identity source) and are the everyday admins, whileadmin-internaladmins are local database accounts (created via the CLI, used for initial setup and as fallback/recovery) that authenticate only at the/authendpoint. Both share theadmin-prefix so a singleuser_role=admin*filter matches either.stris used instead ofStrEnum(3.11+) for compatibility with Python 3.10; the__str__override normalizesstr()/f-string output to the value across versions (mirrorsAuthEventType).- ADMIN_EXTERNAL = 'admin-external'¶
- ADMIN_INTERNAL = 'admin-internal'¶
- USER = 'user'¶
- privacyidea.lib.conditional_access.authentication_event_types.CA_ENFORCEMENT_EVENT_TYPES: frozenset[AuthEventType] = frozenset({AuthEventType.ACCESS_DENIED, AuthEventType.IP_BLOCKED, AuthEventType.USER_LOCKED})¶
The event types conditional access writes for its own rejections, which no policy may count - otherwise a lock would keep refreshing itself on the requests it refuses.
- privacyidea.lib.conditional_access.authentication_event_types.CLIENT_SIGNAL_EVENT_TYPES: frozenset[AuthEventType] = frozenset({AuthEventType.SUSPENDED_API_KEY_USED})¶
Event types that describe the client a request arrived with rather than the outcome of an authentication. They are written to the log and can be filtered and reported on there - which is what they are for - but a policy cannot count them, and they must never be the row that classifies an attempt (see
_count_matching_attempts()), nor stand in for a request that reached an outcome of its own (seeclassifying).Both exclusions are about interference: such a row is staged after the outcome it sits beside, so left in it would replace that outcome - dropping an already-counted failure out of a rate limit, and standing in for the request’s classification so the policies tracking its real outcome are never asked about it.
They are kept out of the trackable vocabulary because no way of counting one does what an administrator would expect. These rows name no user, so a
usertarget never sees them and the defaultDISTINCT_USERSmode of asource_iptarget collapses any number of them into one;PER_ATTEMPTis excluded by the rule above. That leavessource_ipwithPER_REQUESTas the single working combination out of five, and it is the default of neither axis - a policy configured any other way would save, show its events accumulating in the log, and never fire. Offering a vocabulary entry that behaves like that is worse than not offering it, so until such an event can be evaluated in its own right, it is a signal to look at rather than one to count.
- class privacyidea.lib.conditional_access.authentication_event_types.CountMode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
How a conditional-access policy counts the tracked
AuthEventTypes against its stage thresholds. The valid modes depend on the policy target (see_COUNT_MODES_BY_TARGETin the CRUD layer): both targets support the volume modes;DISTINCT_USERSis additionally available for asource_iptarget (and its default).PER_REQUESTcounts individualauthentication_logrows.PER_ATTEMPTcounts whole authentication attempts: the rows sharing oneattempt_idare collapsed into a single attempt, so a multi-request challenge / multichallenge login counts once. Both are volume modes and track the same vocabulary (AuthEventTypenames); the mode only changes the unit that is counted. For asource_iptarget they give plain per-IP rate limiting (raw request / attempt volume from one IP).DISTINCT_USERScounts the number of distinct accounts a subject targeted rather than the volume of events – the password-spraying / enumeration signal for asource_ippolicy (one IP hitting many accounts). It is specific to thesource_iptarget (there is no distinct-accounts notion for a single-user policy).str/Enum(notStrEnum) for Python 3.10, likeAuthEventType.- DISTINCT_USERS = 'DISTINCT_USERS'¶
- PER_ATTEMPT = 'PER_ATTEMPT'¶
- PER_REQUEST = 'PER_REQUEST'¶
- privacyidea.lib.conditional_access.authentication_event_types.EVENT_TYPE_OUTCOME: dict[AuthEventType, AuthEventOutcome] = {AuthEventType.ACCESS_DENIED: AuthEventOutcome.FAILURE, AuthEventType.CHALLENGE_ANSWERED_FAIL: AuthEventOutcome.FAILURE, AuthEventType.CHALLENGE_ANSWERED_OUT_OF_BAND: AuthEventOutcome.PENDING, AuthEventType.CHALLENGE_CANCELLED: AuthEventOutcome.FAILURE, AuthEventType.CHALLENGE_CONTINUED: AuthEventOutcome.PENDING, AuthEventType.CHALLENGE_DECLINED: AuthEventOutcome.FAILURE, AuthEventType.CHALLENGE_DECLINED_UNKNOWN_TRIGGER: AuthEventOutcome.FAILURE, AuthEventType.CHALLENGE_TRIGGERED: AuthEventOutcome.PENDING, AuthEventType.CHALLENGE_TRIGGER_FAIL: AuthEventOutcome.FAILURE, AuthEventType.DEVICE_TOKEN_REUSED: AuthEventOutcome.FAILURE, AuthEventType.ENROLLMENT_CANCELED_FAIL: AuthEventOutcome.FAILURE, AuthEventType.ENROLLMENT_FAIL: AuthEventOutcome.FAILURE, AuthEventType.ENROLLMENT_TRIGGERED: AuthEventOutcome.PENDING, AuthEventType.INVALID_TOKEN_TYPE: AuthEventOutcome.FAILURE, AuthEventType.IP_BLOCKED: AuthEventOutcome.FAILURE, AuthEventType.LOGIN_NAME_NOT_UNIQUE: AuthEventOutcome.FAILURE, AuthEventType.LOGIN_SUCCESS: AuthEventOutcome.SUCCESS, AuthEventType.MFA_FAIL: AuthEventOutcome.FAILURE, AuthEventType.NOT_AUTHORIZED: AuthEventOutcome.FAILURE, AuthEventType.NO_TOKEN: AuthEventOutcome.FAILURE, AuthEventType.NO_USABLE_TOKEN: AuthEventOutcome.FAILURE, AuthEventType.OFFLINE_REFILL_FAIL: AuthEventOutcome.FAILURE, AuthEventType.OFFLINE_REFILL_SUCCESS: AuthEventOutcome.SUCCESS, AuthEventType.PASSWORD_FAIL: AuthEventOutcome.FAILURE, AuthEventType.PIN_FAIL: AuthEventOutcome.FAILURE, AuthEventType.POST_AUTHENTICATION_FAIL: AuthEventOutcome.FAILURE, AuthEventType.SUSPENDED_API_KEY_USED: AuthEventOutcome.FAILURE, AuthEventType.TOKEN_ONLY_FAIL: AuthEventOutcome.FAILURE, AuthEventType.UNKNOWN_FAIL_REASON: AuthEventOutcome.FAILURE, AuthEventType.USER_LOCKED: AuthEventOutcome.FAILURE, AuthEventType.USER_STORE_UNAVAILABLE: AuthEventOutcome.FAILURE, AuthEventType.USER_UNKNOWN: AuthEventOutcome.FAILURE}¶
The
AuthEventOutcomeof everyAuthEventType; read throughoutcome_of().
- privacyidea.lib.conditional_access.authentication_event_types.INTERNAL_CLASSIFICATION_KEYS = frozenset({'authentication_event_reason', 'authentication_event_reason_detail', 'authentication_event_serials', 'authentication_event_type', 'log_autoresync', 'log_transaction_id'})¶
The classification keys stripped at the lib/api boundary, so none of them can reach a client.
- privacyidea.lib.conditional_access.authentication_event_types.NON_REPRESENTATIVE_EVENT_TYPES: frozenset[AuthEventType] = frozenset({AuthEventType.ACCESS_DENIED, AuthEventType.IP_BLOCKED, AuthEventType.SUSPENDED_API_KEY_USED, AuthEventType.USER_LOCKED})¶
Every event type that must never be an attempt’s representative - the row whose type classifies the whole attempt: the rejections conditional access wrote itself, and the signals about the request’s client. What they have in common is that neither is an outcome the attempt reached.
- privacyidea.lib.conditional_access.authentication_event_types.REASON_DETAIL_INFO_KEY = 'reason_detail'¶
Key the reason’s detail dict is stored under inside an entry’s
other_info.
- privacyidea.lib.conditional_access.authentication_event_types.REQUEST_EVENT_PRECEDENCE: list[AuthEventType] = [AuthEventType.NOT_AUTHORIZED, AuthEventType.ENROLLMENT_TRIGGERED, AuthEventType.LOGIN_SUCCESS, AuthEventType.CHALLENGE_ANSWERED_OUT_OF_BAND, AuthEventType.CHALLENGE_CONTINUED, AuthEventType.CHALLENGE_TRIGGERED, AuthEventType.CHALLENGE_DECLINED_UNKNOWN_TRIGGER, AuthEventType.CHALLENGE_ANSWERED_FAIL, AuthEventType.CHALLENGE_DECLINED, AuthEventType.CHALLENGE_CANCELLED, AuthEventType.CHALLENGE_TRIGGER_FAIL, AuthEventType.ENROLLMENT_CANCELED_FAIL, AuthEventType.ENROLLMENT_FAIL, AuthEventType.MFA_FAIL, AuthEventType.TOKEN_ONLY_FAIL, AuthEventType.PASSWORD_FAIL, AuthEventType.PIN_FAIL, AuthEventType.NO_USABLE_TOKEN, AuthEventType.NO_TOKEN, AuthEventType.USER_UNKNOWN, AuthEventType.LOGIN_NAME_NOT_UNIQUE, AuthEventType.USER_STORE_UNAVAILABLE, AuthEventType.INVALID_TOKEN_TYPE, AuthEventType.UNKNOWN_FAIL_REASON, AuthEventType.POST_AUTHENTICATION_FAIL, AuthEventType.DEVICE_TOKEN_REUSED, AuthEventType.SUSPENDED_API_KEY_USED, AuthEventType.OFFLINE_REFILL_SUCCESS, AuthEventType.OFFLINE_REFILL_FAIL]¶
Request-level precedence, highest signal first: which staged event classifies a request that produced several (see
reduce_request_events()).
- class privacyidea.lib.conditional_access.authentication_event_types.RestrictionCause(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Who imposed a live conditional-access restriction: the engine acting on a policy (
POLICY) or an administrator by hand (MANUAL).It is stored on the state row itself because a manual restriction has nowhere else to live. What a policy did is recorded as a
ConditionalAccessOutcomehanging off theauthentication_logrow of the request that triggered it - and a manual lock has no such request. The cause is written together with the expiry, so it always describes the restriction now in force rather than the first one ever written.str/Enum(notStrEnum) for Python 3.10, likeAuthEventType.- MANUAL = 'MANUAL'¶
- POLICY = 'POLICY'¶
- privacyidea.lib.conditional_access.authentication_event_types.SERVER_FAILURE_EVENT_TYPES: frozenset[AuthEventType] = frozenset({AuthEventType.USER_STORE_UNAVAILABLE})¶
Event types that record the server failing to process an authentication rather than anything the request did. They are the outcome of their attempt, but a policy cannot count them: the user did nothing wrong, and while a user store is down every login fails, so counting them would lock users and block the source IPs of every client in front of privacyIDEA for the outage.
- privacyidea.lib.conditional_access.authentication_event_types.UNTRACKABLE_EVENT_TYPES: frozenset[AuthEventType] = frozenset({AuthEventType.ACCESS_DENIED, AuthEventType.IP_BLOCKED, AuthEventType.SUSPENDED_API_KEY_USED, AuthEventType.USER_LOCKED, AuthEventType.USER_STORE_UNAVAILABLE})¶
Every event type a conditional-access policy may not count: the rejections conditional access wrote itself, the signals about the request’s client, and the server failures. The first two are no outcome an authentication attempt reached, which is also why neither may represent one - see
NON_REPRESENTATIVE_EVENT_TYPES. A server failure is the outcome of its attempt and represents it, which is why the two sets answer different questions: one what a policy may count, the other what may stand for an attempt.
- privacyidea.lib.conditional_access.authentication_event_types.build_reason_detail(reasons: dict | None = None, policies: list | None = None) dict | None[source]¶
Build the reason-detail dict recorded under
REASON_DETAIL_INFO_KEY, orNonewhen there is nothing to record.The one place its structure is defined, so every layer that adds to it - the token layer with its per-serial findings, a policy layer with the rules that decided - writes the same shape. The detail is merged on the way into the row (see
reclassify()), so each layer only passes its own half.- Parameters:
reasons – what each token was found to be, keyed by serial
policies – the names of the policies that decided the request
- Returns:
the detail dict, or
Noneif both parts are empty
- privacyidea.lib.conditional_access.authentication_event_types.order_request_reasons(reasons) list[AuthEventReason][source]¶
Order the per-token reasons of one request into the list that goes in the entry’s reason rows, in the order
AuthEventReasondeclares them (token state, then authorization, then the credentials, then challenge-response), with duplicates removed. A request rarely fails for one reason - a user with three tokens can have one revoked, one past its failcount and one that simply got the wrong OTP - and every one of them is recorded, so a filter on any of them finds the request. Which token failed for which reason stays inother_info(seeAUTH_EVENT_REASON_DETAIL_KEY).The order is the vocabulary’s own, deliberately, and says nothing about which reason matters more: they are all recorded and all filterable, so ranking them would be a judgement nobody needs made - and a second list to keep in step with this enum, which a new member could be forgotten from. What the order does buy is determinism: the same findings always read the same way, in the log and in the WebUI.
Values that are not a member are logged and dropped, so a caller that recorded a bare string on
token.auth_detailsdegrades the classification rather than breaking the authentication (mirrorsreduce_request_events()). Accepting plain strings is what keeps that promise: converting them in the caller’s generator would raiseValueErrorpast this guard and turn a mislabelled reason into a failed authentication.- Parameters:
reasons – an iterable of
AuthEventReasonmembers or of their values- Returns:
the known reasons, in vocabulary order and deduplicated; empty if reasons holds none
- privacyidea.lib.conditional_access.authentication_event_types.outcome_of(event_type: AuthEventType) AuthEventOutcome[source]¶
Return the
AuthEventOutcomeof event_type (seeEVENT_TYPE_OUTCOME).
- privacyidea.lib.conditional_access.authentication_event_types.reduce_request_events(events: list[AuthEventType]) AuthEventType | None[source]¶
Reduce the per-token outcomes of one authentication request to the single event that classifies the whole request, by the fixed
REQUEST_EVENT_PRECEDENCE.Events without a defined precedence (e.g. a new
AuthEventTypemember that was not added toREQUEST_EVENT_PRECEDENCE) are logged and ignored, so an oversight degrades the classification rather than breaking the authentication.- Parameters:
events – an iterable of
AuthEventTypemembers- Returns:
the highest-precedence known event, or
Noneif events holds no known event
- privacyidea.lib.conditional_access.authentication_event_types.strip_internal_classification(details)[source]¶
Remove every
INTERNAL_CLASSIFICATION_KEYSentry from details, in place, and return it.The last thing that happens to a response body before it is built (see
prepare_result()andsend_error()), so that a view that forgot to take the classification off a lib call’s reply cannot leak it. Views still pop the keys where they read them - this is the backstop, not the mechanism, and it is deliberately at the boundary rather than in each view, because “every future caller remembers” is exactly what a boundary is for.- Parameters:
details – the reply/details dict about to be answered with, or anything that is not a dict (left alone)
- Returns:
details
17.2.1.5.2. Authentication log¶
- class privacyidea.lib.conditional_access.authentication_log.AuthenticationLogPage(auth_logs: Sequence[AuthenticationLog], count: int, current: int, prev: int | None, next: int | None)[source]¶
One page of an authentication-log query plus its pagination metadata.
- auth_logs: Sequence[AuthenticationLog]¶
- count: int¶
- current: int¶
- next: int | None¶
- prev: int | None¶
- class privacyidea.lib.conditional_access.authentication_log.AuthenticationLogVisibilityScope(realms: list[str], resolvers: list[str], usernames: list[str], uids: list[str] = <factory>, username_case_insensitive: bool = False, user_roles: list[str] = <factory>, excluded_usernames: list[str] = <factory>, excluded_accounts: list[tuple[str, str]] = <factory>)[source]¶
One policy’s target scope, restricting which authentication-log entries an admin may see/delete. An entry must match all dimensions a policy sets (logical AND); across several scopes (from several policies) an entry is visible if it matches any one of them (logical OR) – see
get_authentication_logs_paginate(). Empty lists mean “no restriction on that dimension”.username_case_insensitive mirrors the originating policy’s
user_case_insensitiveoption and forces a case-insensitive match on theusernamesandexcluded_usernamesdimensions only; realm and resolver always match case-sensitively.excluded_usernames leaves these logins out. It is how a policy for every user but some (
"*"with"!name") is expressed, since the users can not be listed the way realms and resolvers are. Like every other dimension it restricts: an entry without a username is not admitted by it.excluded_accounts leaves the entries of these accounts out as well, as
(resolver, uid)pairs: the accounts the excluded logins resolve to. A login is not an identity, so an entry recorded under another login of an excluded account - before a rename, or spelled differently in a case-insensitive user store - would otherwise slip past excluded_usernames. An entry without a uid is only held to excluded_usernames.user_roles restricts to entries of those
AuthLogUserRolevalues. It is not derived from policy scoping (policies do not scope by role); it is used to express a principal’s own entries – a local/internal admin has no realm, so their own entries are matched by username plususer_role=admin-internalinstead of by realm.uids is the resolver’s immutable user id and is only meaningful together with a
resolvers(andrealms) dimension, since a uid is unique per resolver only. It names an account whereusernamesnames a login, which is not an identity: a login can be renamed, and a freed one can be handed to a different account. Policy scoping cannot produce this dimension – a policy targets logins – so it is how a principal’s own entries are expressed (seeown_entries_scope()), matching what the log records the subject as and what the engine counts it by.- excluded_accounts: list[tuple[str, str]]¶
- excluded_usernames: list[str]¶
- realms: list[str]¶
- resolvers: list[str]¶
- uids: list[str]¶
- user_roles: list[str]¶
- username_case_insensitive: bool = False¶
- usernames: list[str]¶
- class privacyidea.lib.conditional_access.authentication_log.ClientLabelSource(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Where a row’s
client_labelcame from: theclient_idrequest parameter the client chose for itself, or the User-Agent header it sent. Recorded because the two are worth very different amounts - one is a name an integration deliberately gives itself, the other is a string any browser sends.str/Enum(notStrEnum) for Python 3.10, likeAuthLogUserRole.- CLIENT_ID = 'client_id'¶
- USER_AGENT = 'user_agent'¶
- class privacyidea.lib.conditional_access.authentication_log.PendingAuthEvent(event_type: ~privacyidea.lib.conditional_access.authentication_event_types.AuthEventType, transaction_id: str | None = None, resolver: str | None = None, uid: str | None = None, realm: str | None = None, username: str | None = None, user_role: str | None = None, source_ip: str | None = None, peer_ip: str | None = None, source_ip_source: str | None = None, client_label: str | None = None, client_label_source: str | None = None, ip_chain: list | None = None, endpoint: str | None = None, serial: str | None = None, attempt_id: str | None = None, other_info: dict | None = None, reasons: list[str] = <factory>, immediate: bool = False, row_id: int | None = None, outcomes: list[~privacyidea.models.conditional_access_outcome.ConditionalAccessOutcome] = <factory>)[source]¶
One authentication-log row, described here rather than written straight away.
The event is the source of truth for its row: assigning to a field is all a later request stage has to do, whether or not the row exists yet. Until it exists the assignment simply lands in the eventual
INSERT; once it exists the event is markedchangedand the next flush issues anUPDATE. Without that, an assignment after the row was written would be lost twice over - skipped by the next flush and invisible to the stored row, since_build_entry()copies the values into a separate ORM object.The values are held raw: truncation to the column lengths happens when the row is built, so a value a later stage lengthens - a post-policy extending
serial, say - is cut against its final length rather than an intermediate one.other_infois likewise the caller’s dict, which the row build merges truncation overflow into.- attempt_id: str | None = None¶
- property changed: bool¶
Whether the stored row is out of date because a field was assigned after it was written.
- client_label: str | None = None¶
- client_label_source: str | None = None¶
- endpoint: str | None = None¶
- event_type: AuthEventType¶
- immediate: bool = False¶
- ip_chain: list | None = None¶
- other_info: dict | None = None¶
- outcomes: list[ConditionalAccessOutcome]¶
- peer_ip: str | None = None¶
- realm: str | None = None¶
- reasons: list[str]¶
- resolver: str | None = None¶
- row_id: int | None = None¶
- serial: str | None = None¶
- source_ip: str | None = None¶
- source_ip_source: str | None = None¶
- transaction_id: str | None = None¶
- uid: str | None = None¶
- user_role: str | None = None¶
- username: str | None = None¶
- property written: bool¶
Whether the row has been committed.
- privacyidea.lib.conditional_access.authentication_log.SORTABLE_COLUMNS: dict[str, InstrumentedAttribute] = {'attempt_id': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'client_label': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'client_label_source': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'endpoint': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'event_type': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'id': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'peer_ip': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'realm': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'resolver': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'serial': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'source_ip': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'source_ip_source': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'timestamp': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'transaction_id': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'uid': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'username': <sqlalchemy.orm.attributes.InstrumentedAttribute object>}¶
The columns a paginated authentication-log query may sort by, keyed by the name the API accepts.
- privacyidea.lib.conditional_access.authentication_log.cleanup_authentication_log(older_than: datetime, chunk_size: int | None = None) int[source]¶
Delete all authentication log entries with a timestamp strictly older than the given datetime.
- Parameters:
older_than – delete entries whose timestamp is older than this (naive or timezone-aware; aware values are converted to UTC)
chunk_size – if given, delete in chunks of this size to avoid long locks / deadlocks on large tables
- Returns:
the number of deleted rows
- privacyidea.lib.conditional_access.authentication_log.delete_authentication_log_event(event_id: int) None[source]¶
Delete a single authentication log entry by id.
A management operation, so a failure surfaces to the caller instead of being swallowed.
- privacyidea.lib.conditional_access.authentication_log.delete_authentication_logs(resolvers: str | list[str] | None = None, uids: str | list[str] | None = None, realms: str | list[str] | None = None, usernames: str | list[str] | None = None, user_roles: str | list[str] | None = None, event_types: str | list[str] | None = None, reasons: str | list[str] | None = None, source_ips: str | list[str] | None = None, serials: str | list[str] | None = None, transaction_ids: str | list[str] | None = None, attempt_ids: str | list[str] | None = None, client_labels: str | list[str] | None = None, client_label_sources: str | list[str] | None = None, peer_ips: str | list[str] | None = None, source_ip_sources: str | list[str] | None = None, endpoints: str | list[str] | None = None, start_time: datetime | None = None, end_time: datetime | None = None, visibility_scopes: list[AuthenticationLogVisibilityScope] | None = None, chunk_size: int | None = None) int[source]¶
Delete all authentication log entries matching the given filters and return the number deleted.
The filter parameters –
resolvers,uids,realms,usernames,user_roles,event_types,reasons,source_ips,serials,transaction_ids,attempt_ids,client_labels,client_label_sources,peer_ips,source_ip_sources,endpoints,start_timeandend_time– behave exactly likeget_authentication_logs()(to delete entries older than a point in time, passend_time). The caller must pass at least one filter: with no filter this would delete the entire log, which this function refuses.- Parameters:
visibility_scopes – restrict the deletion to entries matching any of these scopes (see
visibility_condition());Nonemeans no restrictionchunk_size – if given, delete in chunks of this size to avoid long locks on large tables
- Returns:
the number of deleted entries
- privacyidea.lib.conditional_access.authentication_log.excluded_accounts_condition(resolver_column: ColumnElement, uid_column: ColumnElement, accounts: list[tuple[str, str]]) ColumnElement[bool][source]¶
The condition leaving out the rows of these
(resolver, uid)accounts, seeAuthenticationLogVisibilityScope.excluded_accounts. A row without a uid names no account and is admitted.
- privacyidea.lib.conditional_access.authentication_log.filter_conditions(resolvers: str | list[str] | None = None, uids: str | list[str] | None = None, realms: str | list[str] | None = None, usernames: str | list[str] | None = None, user_roles: str | list[str] | None = None, event_types: str | list[str] | None = None, reasons: str | list[str] | None = None, source_ips: str | list[str] | None = None, serials: str | list[str] | None = None, transaction_ids: str | list[str] | None = None, attempt_ids: str | list[str] | None = None, client_labels: str | list[str] | None = None, client_label_sources: str | list[str] | None = None, peer_ips: str | list[str] | None = None, source_ip_sources: str | list[str] | None = None, endpoints: str | list[str] | None = None, start_time: datetime | None = None, end_time: datetime | None = None, case_insensitive: bool = False) list[source]¶
Build the list of SQLAlchemy
whereconditions for the provided filters (Nonemeans no filter on that field). Each scalar filter accepts a single value or a list of values; an entry matches the field if it equals any of the values, or (for a value containing a*wildcard) matches it with aLIKE. Returned as a list so it can be applied to bothselectanddeletestatements. timestamp filters are inclusive on both ends.reasonsis the one filter that does not match a column of the entry: an entry has a list of reasons, in a table of its own, and matches if any of them matches (see_reason_condition()).With case_insensitive set, plain (non-wildcard) filter values match case-insensitively; wildcard values always match case-insensitively (see
match_condition()).
- privacyidea.lib.conditional_access.authentication_log.get_authentication_log_event(event_id: int) AuthenticationLog | None[source]¶
Return a single AuthenticationLog entry by event_id, with its classified reasons, or None if not found.
The reasons are eagerly loaded because they are
lazy="raise"and a single entry read by id is worth nothing without them; one extra statement for one row is not the fan-out that flag guards against. The conditional-access outcomes are not, soto_dict(include_outcomes=True)still belongs to the paginated listing alone.
- privacyidea.lib.conditional_access.authentication_log.get_authentication_logs(resolvers: str | list[str] | None = None, uids: str | list[str] | None = None, realms: str | list[str] | None = None, usernames: str | list[str] | None = None, user_roles: str | list[str] | None = None, event_types: str | list[str] | None = None, reasons: str | list[str] | None = None, source_ips: str | list[str] | None = None, serials: str | list[str] | None = None, transaction_ids: str | list[str] | None = None, attempt_ids: str | list[str] | None = None, client_labels: str | list[str] | None = None, client_label_sources: str | list[str] | None = None, peer_ips: str | list[str] | None = None, source_ip_sources: str | list[str] | None = None, endpoints: str | list[str] | None = None, start_time: datetime | None = None, end_time: datetime | None = None) Sequence[AuthenticationLog][source]¶
Return authentication log entries matching all provided filter criteria, ordered by id (i.e. chronologically). All parameters are optional; omitting a parameter means no filtering on that field. Each scalar filter accepts a single value or a list of values; an entry matches the field if it equals any of the listed values, or (for a value containing a
*wildcard) matches it with aLIKE. timestamp filters are inclusive on both ends.The entries come with their classified reasons loaded (
lazy="raise"otherwise), which is one extra statement for the whole result: an entry read here is read to be looked at, and its reasons are part of it. The conditional-access outcomes are not - the paginated listing is the one query that reads those.
- privacyidea.lib.conditional_access.authentication_log.get_authentication_logs_paginate(resolvers: str | list[str] | None = None, uids: str | list[str] | None = None, realms: str | list[str] | None = None, usernames: str | list[str] | None = None, user_roles: str | list[str] | None = None, event_types: str | list[str] | None = None, reasons: str | list[str] | None = None, source_ips: str | list[str] | None = None, serials: str | list[str] | None = None, transaction_ids: str | list[str] | None = None, attempt_ids: str | list[str] | None = None, client_labels: str | list[str] | None = None, client_label_sources: str | list[str] | None = None, peer_ips: str | list[str] | None = None, source_ip_sources: str | list[str] | None = None, endpoints: str | list[str] | None = None, ca_action_types: str | list[str] | None = None, ca_policy_names: str | list[str] | None = None, ca_dry_run: bool | None = None, start_time: datetime | None = None, end_time: datetime | None = None, visibility_scopes: list[AuthenticationLogVisibilityScope] | None = None, case_insensitive: bool = False, page: int = 1, page_size: int = 15, sort_column: str = 'id', sort_order: str = 'desc') AuthenticationLogPage[source]¶
Return a single page of authentication log entries matching the given filters.
The filter parameters –
resolvers,uids,realms,usernames,user_roles,event_types,reasons,source_ips,serials,transaction_ids,attempt_ids,client_labels,client_label_sources,peer_ips,source_ip_sources,endpoints,start_timeandend_time– behave exactly likeget_authentication_logs(). Theca_*parameters filter on what conditional access did to the request and are only offered here, since this is the endpoint that reads the outcomes:- Parameters:
ca_action_types – only entries with an outcome of one of these action types;
"*"reads as “conditional access acted on this request at all”ca_policy_names – only entries with an outcome recorded for one of these policy names
ca_dry_run – only entries with a dry-run outcome (
True) or with an enforced one (False);Nonedoes not filtervisibility_scopes – restrict the result to entries matching any of these scopes (see
visibility_condition());Nonemeans no restrictioncase_insensitive – if set, plain (non-wildcard) filter values match case-insensitively; wildcard values always match case-insensitively
page – the page number to return, 1-indexed
page_size – the number of entries per page
sort_column – the column to sort by; one of
SORTABLE_COLUMNS(falling back toid), always tie-broken by id so the order is stable across pagessort_order –
ascordesc
- Returns:
an
AuthenticationLogPagewith the page’s entries and the pagination metadata
- privacyidea.lib.conditional_access.authentication_log.log_authentication_event(event_type: AuthEventType, reasons: list[str] | None = None, transaction_id: str | None = None, resolver: str | None = None, uid: str | None = None, realm: str | None = None, username: str | None = None, user_role: str | None = None, source_ip: str | None = None, peer_ip: str | None = None, source_ip_source: str | None = None, client_label: str | None = None, client_label_source: str | None = None, ip_chain: list | None = None, endpoint: str | None = None, serial: str | None = None, attempt_id: str | None = None, other_info: dict | None = None) int | None[source]¶
Create a new authentication log entry and return its id, or
Noneif it could not be written.The single-event convenience wrapper over
write_authentication_events(), for callers that have no request context to collect on (tests and lib code outside a view; no authentication takes this path, since every authentication reaches the server as a request).
- privacyidea.lib.conditional_access.authentication_log.match_condition(column: InstrumentedAttribute, value: str | list[str] | None, case_insensitive: bool = False) ColumnElement[bool] | None[source]¶
Build the match condition for one column from a single value or a list of values, or
Nonefor no filter on that field. An entry matches if it equals any plain value, or matches any value containing a*wildcard;*is the only wildcard (see_wildcard_pattern()). Plain values are batched into a singleIN; only wildcard values cost aLIKEeach, so a list without wildcards stays a single indexedIN.Plain values are matched with a plain
INso an index on the column can still be used. The match is case-sensitive on every backend. Setting case_insensitive lowers both sides to match case-insensitively instead – note this defeats the column index (theLOWER()wrapper prevents an index seek), so it is the slower path. Wildcard values always match case-insensitively (viaILIKE), since the DB-defaultLIKEcase semantics differ per backend.
- privacyidea.lib.conditional_access.authentication_log.naive_utc(value: datetime) datetime[source]¶
Normalize a datetime to naive UTC, matching how the
timestampcolumn is stored. A timezone-aware value is converted to UTC and stripped of its tzinfo; a naive value is assumed to already be in UTC and returned unchanged. This lets callers pass either form without risking a naive-vs-aware comparison against the column.
- privacyidea.lib.conditional_access.authentication_log.update_authentication_events(events: Sequence[PendingAuthEvent]) bool[source]¶
Re-write the stored rows of events that were amended after being written, as one transaction, and clear their changed flag.
This is what makes a
PendingAuthEventthe source of truth for its row: a later request stage - a post-policy correcting the classification, say - just assigns to the event, and the row is brought back in line here. Like the insert, a failure is logged and swallowed; the events keep their changed flag, so a later flush retries them.- Returns:
whether the transaction was committed
- privacyidea.lib.conditional_access.authentication_log.visibility_condition(scopes: list[AuthenticationLogVisibilityScope]) ColumnElement[bool][source]¶
Build a single
wherecondition restricting the visible entries to the given scopes: an entry must match all dimensions a scope sets (AND), and is included if it matches any one scope (OR). Entries with a NULL value in a restricted dimension are excluded.The visibility scope is an authorization boundary (which entries a principal may see). Each dimension matches by equality via a plain
IN(which keeps the column index), and the excluded usernames viaNOT IN. The boundary columns (realm, resolver, uid, username) are pinned to a case-sensitive collation at the schema level (case_sensitive_unicode():utf8mb4_binon MySQL/MariaDB; SQLite, PostgreSQL and Oracle compare case-sensitively by default), so the match is case-sensitive on every backend rather than depending on the server-default collation. This fails closed: an admin scoped to resolverresor useralicenever sees a distinctRes/Alice.The one exception is the username dimension when the originating policy set
user_case_insensitive(carried on the scope): it is then matched case-insensitively viaLOWER()on both sides – only this dimension, mirroring how that policy option is applied during policy matching. realm and resolver are always case-sensitive (realm is additionally always stored lower case, so its casing never varies in practice).A scope that names no
user_rolesdoes not reach the rows of a local database administrator. Realm, resolver and user are userstore terms, and none of them describes such an account, whose row carries a login name and nothing else, so a boundary drawn only in those terms does not contain one. Without this, a policy scoped to a user name would reach a local admin of that name - by coincidence of the sharedusernamecolumn rather than by anyone’s intent, and the admin policy the boundary comes from has no way to say otherwise, carrying only realm, resolver and user (seeget_policy_visibility_scopes()). A local admin’s rows are therefore reachable only by a caller that is unscoped altogether, or by a scope naming the role outright - which is how a scoped admin still sees their own entries.An empty scope list (or scopes that set no dimension at all) restricts to nothing: it returns
false()rather than an emptyor_(), so the visibility boundary fails closed instead of degrading to “no restriction”.
- privacyidea.lib.conditional_access.authentication_log.write_authentication_events(events: Sequence[PendingAuthEvent]) bool[source]¶
Insert events as one transaction, in the given order, and record each row’s id on its event.
Writing the authentication log must never break the authentication itself, so a failure is logged and swallowed and the events keep
row_id is None- which makes them eligible for a later retry. The insert runs on the conditional-access session, so neither the commit nor a rollback touches the request’s own pending writes.- Returns:
whether the transaction was committed
17.2.1.5.3. Statistics over the log¶
Aggregate reads over the authentication log: how attempts ended, and what conditional access did.
Two summaries live here, both answer a question about one time window cut into equal buckets, both hand that window
and those buckets back in the same shape, and both are built from the same machinery – _bin_edges(),
_bin_column() and the window normalization around them. Splitting them apart would duplicate that machinery;
keeping them beside the listing and the write path left one module carrying five unrelated concerns.
The bucketing is deliberately a SUM(CASE ...) column per bin rather than a per-dialect date function, so one
portable statement serves every supported database. MAX_STATISTICS_BINS therefore bounds the width of the
generated statement rather than the rows it reads.
The attempt reduction uses a window function (ROW_NUMBER), because an attempt’s
representative is chosen by a column pair and no aggregate ranks on one.
- class privacyidea.lib.conditional_access.authentication_log_statistics.AuthenticationEventSeries(event_type: str, outcome: str | None, counts: list[int])[source]¶
One classification of an attempt-level statistics result: how many authentication attempts ended a given way, bucketed over the window’s bins.
event_type is the
AuthEventTypeof the event that classified the attempt – its representative, seeget_authentication_log_statistics()– so it names how these attempts ended, not an event they merely passed through on the way there.outcome is the
AuthEventOutcomeof event_type (success,failureorpending), orNoneif the stored value is not a knownAuthEventType. It is resolved here so that grouping the series by result does not mean re-deriving the mapping.counts holds one attempt count per bin, in bin order, always as many entries as the result has bins: a bucket where nothing happened is a
0rather than a gap, so the series can be charted without being re-aligned. The bins’ start times are not repeated here – every series shares them, so they live on the enclosingAuthenticationLogStatistics.- counts: list[int]¶
- event_type: str¶
- outcome: str | None¶
- to_dict() dict[source]¶
Serialize the series for the API response, including the window total a caller would otherwise re-sum.
- property total: int¶
How many attempts this classification holds across the whole window.
- class privacyidea.lib.conditional_access.authentication_log_statistics.AuthenticationLogStatistics(start_time: datetime, end_time: datetime, bin_starts: list[datetime], events: list[AuthenticationEventSeries])[source]¶
Attempt-level statistics over one time window: one
AuthenticationEventSeriesper classification, all sharing the same bins.start_time and end_time are the window the result covers, normalized to naive UTC like the
timestampcolumn and inclusive at both ends, so a caller that passed timezone-aware values gets back the instants that were actually queried.bin_starts holds the inclusive start of each bucket, one entry per bin and in the same order as every series’ counts, so the two zip together. The buckets are of equal width and cover the window exactly; only the last one closes inclusively, on end_time.
events holds one series per classification present in the window: a classification no attempt ended with has no series at all rather than an all-zero one, so a missing entry reads as zero. They are ordered by descending window total, ties broken by event type, so a caller wanting the top few can slice. Every classification is offered,
CA_ENFORCEMENT_EVENT_TYPESincluded; which of them to show is the view’s decision (seeget_authentication_log_statistics()for why they are reduced with and dropped only afterwards).- bin_starts: list[datetime]¶
- end_time: datetime¶
- events: list[AuthenticationEventSeries]¶
- start_time: datetime¶
- to_dict() dict[source]¶
Serialize the statistics for the API response, timestamps as ISO-8601 UTC strings like
AuthenticationLog.to_dict().The series sit under their own
eventskey so a second section – aggregating what conditional access did, fromconditional_access_outcome, rather than how attempts ended – can be added later without breaking the response.
- property total: int¶
How many attempts the window holds across all classifications.
- class privacyidea.lib.conditional_access.authentication_log_statistics.ConditionalAccessOutcomeSeries(action_type: str, counts: list[int])[source]¶
One action type of an outcome-history result: how many times conditional access did that thing, bucketed over the window’s bins.
action_type is a
ConditionalAccessActionvalue – the action the engine executed (LOCK_USER,BLOCK_IP,EMAIL_ADMIN, …) or theDENYdecision.counts holds one count per bin, in bin order, always as many entries as the result has bins: a bucket where nothing happened is a
0rather than a gap, so the series can be charted without being re-aligned. The bins’ start times are not repeated here – every series shares them, so they live on the enclosingConditionalAccessOutcomeStatistics.- action_type: str¶
- counts: list[int]¶
- to_dict() dict[source]¶
Serialize the series for the API response, including the window total a caller would otherwise re-sum.
- property total: int¶
How many outcomes of this action type the window holds.
- class privacyidea.lib.conditional_access.authentication_log_statistics.ConditionalAccessOutcomeStatistics(start_time: datetime, end_time: datetime, bin_starts: list[datetime], outcomes: list[ConditionalAccessOutcomeSeries])[source]¶
The history of what conditional access did over one time window: one
ConditionalAccessOutcomeSeriesper action type, all sharing the same bins.The window and the bins mean exactly what they do on
AuthenticationLogStatistics– normalized to naive UTC, inclusive at both ends, one bin_starts entry per bucket in the same order as every series’ counts – so a caller charting both reads them the same way.outcomes holds one series per action type present in the window, ordered by descending window total with ties broken by action type. An action nothing triggered has no series at all rather than an all-zero one, so a missing entry reads as zero.
- bin_starts: list[datetime]¶
- end_time: datetime¶
- outcomes: list[ConditionalAccessOutcomeSeries]¶
- start_time: datetime¶
- to_dict() dict[source]¶
Serialize the statistics for the API response, timestamps as ISO-8601 UTC strings like
AuthenticationLog.to_dict().windowandbinsare shaped exactly asAuthenticationLogStatistics.to_dict()shapes them, so a client charting either can share the code that reads them; only the series key differs, naming what these series are grouped by.
- property total: int¶
How many outcomes the window holds across all action types.
- privacyidea.lib.conditional_access.authentication_log_statistics.DEFAULT_STATISTICS_BINS = 48¶
Bins a statistics query splits its window into when the caller names no number.
- privacyidea.lib.conditional_access.authentication_log_statistics.MAX_STATISTICS_BINS = 100¶
Upper bound on the bins the statistics query splits its window into. Each bin becomes one SUM(CASE …) column, so the cap bounds the width of the generated statement rather than the rows it reads.
- privacyidea.lib.conditional_access.authentication_log_statistics.get_authentication_log_statistics(start_time: datetime, end_time: datetime, bins: int = 48, resolvers: list[str] | None = None, uids: list[str] | None = None, realms: list[str] | None = None, usernames: list[str] | None = None, user_roles: list[str] | None = None, event_types: list[str] | None = None, reasons: list[str] | None = None, source_ips: list[str] | None = None, serials: list[str] | None = None, transaction_ids: list[str] | None = None, attempt_ids: list[str] | None = None, client_labels: list[str] | None = None, endpoints: list[str] | None = None, visibility_scopes: list[AuthenticationLogVisibilityScope] | None = None, case_insensitive: bool = False) AuthenticationLogStatistics[source]¶
Summarize the authentication log over
[start_time, end_time]as attempts, bucketed into bins equal-width buckets and grouped by the event type that classifies each attempt.Counting rows here would be wrong twice over: a challenge-response login writes both a
AuthEventType.CHALLENGE_TRIGGEREDand aAuthEventType.LOGIN_SUCCESSrow, so one successful login would be counted as both a pending and a successful event. The rows sharing anattempt_idare therefore reduced to one representative each, by the same rule as_count_matching_attempts(): theLOGIN_SUCCESSrow if the attempt ever logged in, otherwise the latest row by(timestamp, id)(see_row_order()). Insertion order, not an event-type ranking, is what distinguishes a wrong answer then a continue (in progress) from a continue then a wrong answer (failed).The reduction deliberately diverges from the engine’s in two ways, because the engine feeds a threshold while this feeds a human:
The engine drops
CA_ENFORCEMENT_EVENT_TYPESrows before reducing, so a rejection cannot replace a tracked failure and stall an escalation. Dropping them first here would classify an attempt of[CHALLENGE_TRIGGERED, USER_LOCKED]as pending, inventing an in-flight attempt out of one that was turned away. They are reduced with instead, and every classification is returned; a caller that does not want them drops those series, which is filtering rather than misreporting.The engine groups rows by
attempt_idin a dict, so rows without one collapse under a singleNonekey. Harmless for one subject’s handful of rows, and badly wrong when aggregating every subject in a deployment, so a row without anattempt_idcounts as its own attempt here.
Every filter except the window applies to the representative row, not to the rows feeding the reduction: dropping rows from the inner query would reduce an attempt from a subset of its own rows, which misclassifies it rather than excluding it (the same trap
_count_attempts()documents). Which attempts are reduced is narrowed, though - to those holding at least one matching row, an attempt without one having no matching representative either - so a filtered or visibility-scoped summary does not group every row the window holds across the deployment before answering about a few.event_typestherefore reads as “attempts that ended like this”, which is the only meaning it can have once rows are collapsed, andreasonsas “ended for one of these reasons” - it matches the representative’s reason rows, not those of the earlier rows the attempt is reduced from. Each filter takes a list, matching an attempt whose representative equals any of its values or matches any value carrying a*wildcard (seematch_condition()). An attempt straddlingstart_timeis reduced from its in-window rows alone and may be classified by them; this is the same window-edge approximation the engine’s sliding window accepts.- Parameters:
start_time – start of the window, inclusive (naive values are read as UTC)
end_time – end of the window, inclusive
bins – how many equal-width buckets to split the window into, at most
MAX_STATISTICS_BINSvisibility_scopes – restrict the counted attempts to those whose representative matches any of these scopes (see
visibility_condition());Nonemeans no restrictioncase_insensitive – if set, plain (non-wildcard) filter values match case-insensitively
- Returns:
an
AuthenticationLogStatisticsholding one series per classification- Raises:
ParameterError – if the window does not end after it starts, or bins is out of range
- privacyidea.lib.conditional_access.authentication_log_statistics.get_conditional_access_outcome_statistics(start_time: datetime, end_time: datetime, bins: int = 48, action_types: str | list[str] | None = None, policy_names: str | list[str] | None = None, dry_run: bool | None = None, visibility_scopes: list[AuthenticationLogVisibilityScope] | None = None, case_insensitive: bool = False) ConditionalAccessOutcomeStatistics[source]¶
Summarize what conditional access did over
[start_time, end_time], as counts of recorded outcomes bucketed into bins equal-width buckets and grouped by action type.This answers “when were users locked and IPs blocked”, which no other table can:
user_lock_stateandblock_listhold the restriction currently in force and forget it once it lapses, whileConditionalAccessOutcomekeeps one row per action the engine executed. A lock that has since expired, been reset or been purged from the live state is still counted here.Counted per outcome, not per request or per attempt, which is what makes the numbers mean what they say: one row is one restriction imposed. A request that locked the user and blocked the source IP created two restrictions and contributes to both series, once each. This is the opposite of the listing’s filter, which uses an
EXISTSprecisely to avoid multiplying an entry by its outcomes (see_outcome_condition()); here the multiplication is the count.Not to be confused with the enforcement event types of
get_authentication_log_statistics():AuthEventType.USER_LOCKEDis a request turned away by a lock already in force, so counting those would count retries against one lock rather than the lock. The lock itself is aConditionalAccessAction.LOCK_USERoutcome, which is what this counts.The window is filtered on the parent row’s
timestamp, since an outcome deliberately does not repeat it, and the parent is joined for that. Filtering by action_types is what makes the query cheap: it is served byix_ca_outcome_actionand highly selective, so the work scales with how many restrictions were imposed rather than with how many requests the window holds.visibility_scopes likewise applies to the parent row, an outcome carrying no subject of its own. Omitting it would let a realm-scoped admin count every realm’s locks, so it is threaded through exactly as the two log endpoints do.
- Parameters:
start_time – start of the window, inclusive (naive values are read as UTC)
end_time – end of the window, inclusive
bins – how many equal-width buckets to split the window into, at most
MAX_STATISTICS_BINSaction_types – only outcomes of these
ConditionalAccessActionvalues; takes a list and a*wildcard like every other filter on the log, so"*"reads as “everything conditional access did”policy_names – only outcomes recorded for these policy names (the denormalized copy, so a deleted policy is still matchable)
dry_run –
Falsefor only enforced outcomes,Truefor only the dry-run rows recording what would have happened,Nonefor both – note that counting both together charts restrictions that never existedvisibility_scopes – restrict the counted outcomes to those whose request matches any of these scopes (see
visibility_condition());Nonemeans no restrictioncase_insensitive – if set, plain (non-wildcard) filter values match case-insensitively
- Returns:
a
ConditionalAccessOutcomeStatisticsholding one series per action type- Raises:
ParameterError – if the window does not end after it starts, or bins is out of range
17.2.1.5.4. Conditional access outcome log¶
What conditional access did, and how it becomes the history of a request.
The engine judges a request; it does not write history. It builds transient
ConditionalAccessOutcome instances with
outcome_for_stage() (no auth_log_id yet) and returns them, and the request context has them recorded here once
the request’s authentication-log row exists. That is what keeps the engine free of both Flask and the id of a row it
never sees, and it is what makes the pre-auth decision recordable at all: that runs before any log row is written, so
its outcome has to be carried rather than stored on the spot.
The model is deliberately left as schema only. Deriving an outcome from a policy and a stage is domain knowledge of this
layer, not of the table - and a model that reached for ConditionalAccessPolicy could not even import it, since
models/__init__ loads conditional_access_outcome before conditional_access_policy.
Outcomes are only ever written from here. They are rows of the conditional-access subsystem, so they must go on its
session, where a failure cannot roll back the request’s own work: never call save() on one.
This is the queryable history the state tables cannot provide: user_lock_state and block_list show the
restriction in force now and forget it the moment it lapses.
Nothing here is read back on the authentication path. The engine counts over the authentication log, never over this
table (see ConditionalAccessOutcome), so this module only ever
writes.
Two things are deliberately not recorded here, so their absence is not read as a bug:
An action the engine recognized but skipped - an invalid lock duration, an email without a recipient, a never-block IP. Only what happened is stored, so counting rows answers “how often was this user locked” without a filter; the
log.warningeach skip emits is the record of the misconfiguration.An admin lifting a lock or a block. That is a management operation whose interesting fact is who did it under which authorization, which the audit log records and this table has no column for (nor an authentication-log row to hang it on).
- privacyidea.lib.conditional_access.outcome_log.get_outcomes(auth_log_id: int) Sequence[ConditionalAccessOutcome][source]¶
Return the conditional-access outcomes recorded for one authentication-log row, oldest first.
A single-row lookup for the CLI and the test suite. The WebUI does not use it: the log listing loads a whole page’s outcomes in one batched query instead (see
get_authentication_logs_paginate()), because one query per entry would multiply with the page size.
- privacyidea.lib.conditional_access.outcome_log.outcome_for_stage(policy: ConditionalAccessPolicy, stage: ConditionalAccessPolicyStage, action_type: str, event_count: int, *, dry_run: bool = False, expires_at: datetime | None = None) ConditionalAccessOutcome[source]¶
Describe what one action of stage did (or, in dry run, would have done), copying out of the policy configuration what the history has to keep on its own: the policy name, the threshold and the stage name. Deliberately not the policy’s id - see
ConditionalAccessOutcomeon why a recycled id is worse than no id.The result is transient -
auth_log_idis left unset, because the engine that calls this has no row to point at yet - andrecord_outcomes()supplies it and writes the row.This lives in the lib layer rather than on the model on purpose: which policy fields an outcome denormalizes, and that a stage is identified by its threshold, is conditional-access domain knowledge. The table only has to store it.
- Parameters:
policy – the deciding policy
stage – the triggered stage
action_type – the action that ran. Hinted
strrather thanConditionalAccessAction: that enum is astrsubclass, so a member satisfies it, and it lives in the engine - which imports this moduleevent_count – the count that tripped the stage
dry_run – the policy was in dry run, so nothing was actually done
expires_at – the expiry the action wrote, or would have written in dry run. Kept a typed parameter so call sites stay readable, and recorded in the row’s
info(see_restriction_info()); an action with nothing to expire simply omits it.
- privacyidea.lib.conditional_access.outcome_log.record_outcomes(outcomes: Sequence[ConditionalAccessOutcome], auth_log_id: int | None) bool[source]¶
Record outcomes as the conditional-access history of the authentication-log row auth_log_id.
The outcomes arrive transient, as the engine built them, and are stamped with auth_log_id here.
All outcomes of one request are written as a single transaction. That does not conflict with
guarded_write()’s “one write per block” rule, which exists to keep two row locks in different tables from being held at once: these are inserts into a single table, so there is no lock order to get wrong (the same reasonwrite_authentication_events()batches its inserts).Writing history must never break the response that produced it, so a failure is logged and swallowed. The caller keeps the outcomes, which makes a later retry possible.
Without an auth_log_id the outcomes are dropped rather than stored: every outcome belongs to the request that caused it, and the columns this table does not carry - the subject, the time - are only reachable through that row. A missing row therefore means the request never wrote one, which is either legitimate (a poll carries no authentication event) or a bug in the logging, and in neither case is a parentless outcome the right answer.
- Parameters:
outcomes – what the engine decided or did, in the order it happened
auth_log_id – id of the request’s authentication-log row
- Returns:
whether the outcomes are now stored (
Truefor an empty outcomes, nothing to do)
17.2.1.5.5. Conditional access engine¶
- privacyidea.lib.conditional_access.engine.ACTION_SEVERITY: tuple[ConditionalAccessAction, ...] = (ConditionalAccessAction.PERMANENT_LOCK_USER, ConditionalAccessAction.PERMANENT_BLOCK_IP, ConditionalAccessAction.LOCK_USER, ConditionalAccessAction.BLOCK_IP, ConditionalAccessAction.DENY, ConditionalAccessAction.EMAIL_USER, ConditionalAccessAction.EMAIL_ADMIN)¶
Every action, most severe first - the one severity ordering there is, so an action reads the same wherever it is met. It ranks the messages of the restrictions a request is refused by (
rank_and_deduplicate()) and orders the suggestions the policy editor offers (DEFAULT_ERROR_MESSAGES). Both consumers filter it to what they cover - only a restriction in force or a denial has anything to say - so an action that reports nothing to the user still belongs here, ranked, against the day it does.
- class privacyidea.lib.conditional_access.engine.AccessDecision(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
The verdict of the pre-auth conditional-access decision step (
evaluate_access_decision()) for a single request.DENYrejects the current request outright (no persistent state is written);CONTINUEis the default (“no policy denied this request”) and lets the normal flow proceed. It maps to theConditionalAccessAction.DENYstage action, which - unlike the lock/email/block actions - decides the current request and so is handled here, before authentication, rather than in the post-response engine.Two states rather than a bool, because “no policy had an opinion” and “a policy said yes” are worth telling apart in the logs, and because the enum can grow if another standing verdict is ever added.
- CONTINUE = 'CONTINUE'¶
- DENY = 'DENY'¶
- class privacyidea.lib.conditional_access.engine.AccessDecisionResult(decision: ~privacyidea.lib.conditional_access.engine.AccessDecision = AccessDecision.CONTINUE, outcomes: list[~privacyidea.models.conditional_access_outcome.ConditionalAccessOutcome] = <factory>, error_message: str | None = None)[source]¶
The verdict of the pre-auth decision step plus the outcomes it produced.
A
DENYyields an outcome (enforced or dry-run); aCONTINUEyields none, since a policy with no opinion has nothing to record.One type for a single policy’s contribution (
_policy_access_decision()) and for the whole evaluation (evaluate_access_decision()). Hence the default:AccessDecision.CONTINUEreads “this policy has no opinion” for the one and “no policy decided” for the other - which is whatCONTINUEalready means, so nothing needs a separateNoneto say it.- decision: AccessDecision = 'CONTINUE'¶
- error_message: str | None = None¶
- outcomes: list[ConditionalAccessOutcome]¶
- class privacyidea.lib.conditional_access.engine.ConditionalAccessAction(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Action types a
ConditionalAccessPolicyStagecan execute when its failure threshold is met.LOCK_USER,PERMANENT_LOCK_USER,EMAIL_ADMIN,EMAIL_USER,BLOCK_IPandPERMANENT_BLOCK_IPare post-response side effects executed byevaluate_conditional_access_policies().DENYdecides the current request and is therefore handled by the pre-auth decision step (evaluate_access_decision()) instead. The action table stores the string value, so the enum can grow without a schema change.An exemption is expressed as an applicability condition on the policy being exempted from (
USER_REALM NOT_IN [...]), not as an action: conditions are the only scoping mechanism, and a policy whose conditions do not match is skipped in both phases, so the exemption covers the lock, block and email actions as well as theDENY.The
PERMANENT_*variants ignoreaction_valueand never expire (only an admin reset clears them); the timedLOCK_USER/BLOCK_IPread a duration fromaction_valueand a missing/invalid one is a skipped misconfiguration (never silently permanent).stris used instead ofStrEnum(3.11+) for compatibility with Python 3.10, mirroringAuthEventType.- BLOCK_IP = 'BLOCK_IP'¶
- DENY = 'DENY'¶
- EMAIL_ADMIN = 'EMAIL_ADMIN'¶
- EMAIL_USER = 'EMAIL_USER'¶
- LOCK_USER = 'LOCK_USER'¶
- PERMANENT_BLOCK_IP = 'PERMANENT_BLOCK_IP'¶
- PERMANENT_LOCK_USER = 'PERMANENT_LOCK_USER'¶
- class privacyidea.lib.conditional_access.engine.ConditionalAccessEvaluation(outcomes: list[~privacyidea.models.conditional_access_outcome.ConditionalAccessOutcome] = <factory>, enforced_targets: set[~privacyidea.lib.conditional_access.engine.ConditionalAccessTarget] = <factory>)[source]¶
What one post-response evaluation produced: the outcomes to record as the request’s conditional-access history, and which targets it actually left a restriction on.
Engine-internal.
evaluate_conditional_access_policies()hands its caller the outcomes alone, since a restriction says nothing on the request that trips it and there is nothing else for the caller to do with the targets. They are carried this far because the outcomes are only trustworthy once checked against them - see_restrictions_standing().The engine returns the outcomes instead of writing the history itself. It has no access to the id of the authentication-log row (it runs before the row exists on the pre-auth path, and never sees it on the other), and keeping the write out of here is what leaves the engine free of Flask and of the request lifecycle - see
privacyidea.lib.conditional_access.outcome_log.Also used as the per-policy result inside
_evaluate_policy(), since “what this produced” is the same shape for one policy and for all of them.- enforced_targets: set[ConditionalAccessTarget]¶
Which rows this evaluation left a restriction on, as the writes reported it.
evaluate_conditional_access_policies()checks it against what_restrictions_standing()reads back, so a write that claimed a restriction no later request would be refused by records nothing.
- outcomes: list[ConditionalAccessOutcome]¶
- class privacyidea.lib.conditional_access.engine.ConditionalAccessTarget(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
The identity a policy counts, thresholds, and enforces against.
USER(the default) counts one user’s failures over the window and locks that user.SOURCE_IPcounts a single source IP’s activity - by default the distinct users it fails against (spraying), or plain request / attempt volume in the other count modes - and blocks that IP. The value drives what the threshold keys on and what the action targets (so the allowed actions differ by target, enforced in the CRUD layer); the count mode within a target is a separate axis (seeCountMode).stris used instead ofStrEnum(3.11+) for compatibility with Python 3.10, mirroringConditionalAccessAction.- SOURCE_IP = 'source_ip'¶
- USER = 'user'¶
- class privacyidea.lib.conditional_access.engine.LockSubject(resolver: str, uid: str, realm: str, username: str | None = None, internal_admin: bool = False)[source]¶
The principal a
user-target policy counts the failures of and writes the lock for.Two kinds of principal can be locked, and they are identified differently - which is the whole reason this type exists, a single
(resolver, uid, realm)tuple being able to name only the first of them:a resolved user, identified by that tuple, exactly as the authentication log stores it;
a local database admin, who has no resolver, no uid and no realm - only a login name. Their log rows are identified by
usernametogether withuser_role='admin-internal', the same pair the log’s own visibility scoping identifies them by (seeAuthenticationLogVisibilityScope).
The state row keys both shapes on the same three columns (see
UserLockState): a local admin is stored with an empty resolver and realm and the login name as the uid. That can never be mistaken for a user, whose row is only ever written for a principal with all three set - which is what_resolved()means, and what the manuallock_user()enforces as well. So only the log filters differ between the shapes, and they are the one thing this is asked for on the counting path.Build one through
for_user()orfor_internal_admin()rather than by hand: each answersNonefor a principal it cannot identify, which is how “nobody here to count or lock” reaches the callers.- classmethod for_internal_admin(username: str | None) LockSubject | None[source]¶
The subject for the local database admin username, or
Nonewith no name to key on.username has to be the spelling the
admintable stores, which is whatlog_authentication()records: both the count and the row match it case-sensitively, while the lookup that authenticated them need not have.
- classmethod for_user(user: User | None) LockSubject | None[source]¶
The subject for user, or
Nonewhen they are not fully resolved (an unknown login, or a local admin, who arrives here as an empty user) and so carry no identity tuple to count or lock by.
- internal_admin: bool = False¶
Which of the two shapes this is. Not derived from the empty resolver/realm, so what a row means never has to be inferred from what it lacks.
- property log_filters: list[ColumnElement[bool]]¶
The
authentication_logpredicates that select this principal’s rows.A user’s three are in the column order of
ix_authlog_user_event_time/ix_authlog_user_time, so the counts are index range scans. A local admin’s pair matches neither index - their rows carry no resolver, uid or realm at all - and is served byix_authlog_admin_event_time/ix_authlog_admin_time, which pair up the same way: the event count uses the one carryingevent_type, the attempt count the one that ranges ontimestampdirectly.
- realm: str¶
- resolver: str¶
- property state_key: tuple[str, str, str]¶
The
UserLockStateprimary key of this subject.
- uid: str¶
- username: str | None = None¶
The login name: the identity itself for a local admin, and for a user the login the state row denormalizes so a management view can name them without a live resolver lookup.
- privacyidea.lib.conditional_access.engine.MAX_LOCK_DURATION_SECONDS = 250000000000¶
The largest duration (in seconds) a LOCK_USER / BLOCK_IP action may store. Chosen to sit just under where now + timedelta(seconds=duration) (engine.py’s LOCK_USER/BLOCK_IP execution) starts raising OverflowError - computed exactly as 251_612_956_799 seconds (datetime.max - a 2026 “now”), so this is that value with a large safety margin rather than a rounder, smaller number: a smaller cap would reject a duration that used to parse and execute successfully before this bound existed, which is a behavior change this fix does not need to make to close the actual bug. Without any cap, a policy carrying a duration past the true boundary saves successfully and then never actually locks or blocks anyone - the blanket except Exception around action execution swallows the OverflowError and only logs it - silently defeating the very restriction the policy was configured for. Deliberately not equal to policy.py’s MAX_COLUMN_INT: that bound exists for actual database-column widths, and action_value (this field’s own storage) is JSON, so no column width applies here.
- privacyidea.lib.conditional_access.engine.NEVER_BLOCK_CONFIG_KEY = 'PI_CONDITIONAL_ACCESS_NEVER_BLOCK'¶
App-config key holding the never-block allowlist, set in pi.cfg or through the
PRIVACYIDEA_-prefixed environment variable of the same name. This lives in the server configuration and not in the system config on purpose: it is the safety net that keeps an admin from locking themselves out, so it must not be reachable through the very API an attacker (or a mistaken BLOCK_IP policy) could be attacking.
- privacyidea.lib.conditional_access.engine.REPORTING_ACTIONS: frozenset = frozenset({ConditionalAccessAction.BLOCK_IP, ConditionalAccessAction.DENY, ConditionalAccessAction.LOCK_USER, ConditionalAccessAction.PERMANENT_BLOCK_IP, ConditionalAccessAction.PERMANENT_LOCK_USER})¶
The actions whose effect a request can ever be told about: the ones that restrict a target, plus
DENY. A message is said by the pre-check refusing a restricted request - off the row in force - or by the pre-auth decision that denies one, so a stage carrying none of these turns no request away and its wording has nowhere to be shown. What an action does is the property here, which is why this is not read off the table of default wording (DEFAULT_ERROR_MESSAGES): that table happens to cover exactly these actions today, but it answers “which actions have a default sentence”, and an editing convenience added to or taken from it must not silently change what the editor believes can report.
- privacyidea.lib.conditional_access.engine.RESTRICTED_TARGET_BY_ACTION: dict[ConditionalAccessAction, ConditionalAccessTarget] = {ConditionalAccessAction.BLOCK_IP: ConditionalAccessTarget.SOURCE_IP, ConditionalAccessAction.LOCK_USER: ConditionalAccessTarget.USER, ConditionalAccessAction.PERMANENT_BLOCK_IP: ConditionalAccessTarget.SOURCE_IP, ConditionalAccessAction.PERMANENT_LOCK_USER: ConditionalAccessTarget.USER}¶
The target a restricting action writes to, so what a stage claims to have restricted can be checked against the row that ended up in force (see
_restrictions_standing()).
- privacyidea.lib.conditional_access.engine.RESTRICTION_ACTIONS: dict[tuple[ConditionalAccessTarget, bool], ConditionalAccessAction] = {(ConditionalAccessTarget.SOURCE_IP, False): ConditionalAccessAction.BLOCK_IP, (ConditionalAccessTarget.SOURCE_IP, True): ConditionalAccessAction.PERMANENT_BLOCK_IP, (ConditionalAccessTarget.USER, False): ConditionalAccessAction.LOCK_USER, (ConditionalAccessTarget.USER, True): ConditionalAccessAction.PERMANENT_LOCK_USER}¶
The action that restricts a given target for a given duration - and so the action a stored restriction is described by. A row remembers its subject and its expiry but not which action wrote it; it does not need to, because those two facts name the action exactly.
- class privacyidea.lib.conditional_access.engine.RestrictionStatus(permanent: bool, expires_at: datetime | None, seconds_remaining: int | None, target: ConditionalAccessTarget, error_message: str | None = None)[source]¶
The state of an active conditional-access restriction on a single identity: a user lock (
get_user_lock()) or a source-IP block (get_ip_block()). Both return this same shape so callers (e.g. the/authrejection messages) can treat them uniformly.- Variables:
permanent –
Truefor a restriction that only an admin reset clears.expires_at – naive-UTC expiry of a timed restriction, or
Nonewhen permanent.seconds_remaining – whole seconds until a timed restriction expires (
>= 0), orNonewhen permanent.target – whose restriction it is. Part of describing one, and what lets a row with no error message of its own be described by the default error message for its shape: the row does not record which action wrote it, but target and
permanenttogether name that action exactly.error_message – the message template stored on the restriction when it was applied, or
Noneto say nothing. Rendered withrender_error_message(); kept as the template rather than finished text so{duration}reflects the time left now, not at lock time. A permanent restriction has no time left, so that tag is left as written.
- error_message: str | None = None¶
- expires_at: datetime | None¶
- permanent: bool¶
- seconds_remaining: int | None¶
- target: ConditionalAccessTarget¶
- class privacyidea.lib.conditional_access.engine.StageMessage(text: str, action: ConditionalAccessAction)[source]¶
One user-facing message describing a restriction in force, already rendered (see
restriction_messages()).- Variables:
text – what to show;
{duration}is substituted here, against the time the restriction has left now.action – the action this message is about, which ranks it (
ACTION_SEVERITY) so a caller showing several leads with the one the user can do least about. Named by the row’s own target and expiry rather than by the action that happened to write it (seeRESTRICTION_ACTIONS).
- action: ConditionalAccessAction¶
- text: str¶
- privacyidea.lib.conditional_access.engine.can_be_locked(context: CAContext) bool[source]¶
Whether any policy that is able to lock a user applies to the request context describes.
Asked wherever a lock row has to be weighed against a principal it was not written for - the one such place being
_evaluate_rejection(), which reads a same-named user’s lock for a login name that is also a local database admin’s. A principal every locking policy excludes has been declared unlockable by the operator, and a row written for somebody else must not lock them after all: an applicability condition is the only way to say “not this principal”, so it has to hold on every path that can refuse one, not only on the path that writes the row.dry_runpolicies are left out. They enforce nothing, so a principal they cover is not thereby a principal the operator meant to be lockable.- Parameters:
context – what is known about the request under evaluation
- Returns:
True if some enabled, enforcing policy with a user-locking action applies to this request
- privacyidea.lib.conditional_access.engine.canonical_block_identifier(identifier: str) str | None[source]¶
The spelling under which identifier is stored in
BlockList, orNoneif it is not an IP address at all.The table is keyed by the identifier itself and the authentication pre-check looks a block up by primary key, so a row filed under a second spelling of one address is a block that never matches. One IPv6 address has many spellings, and the two writers do not agree on one by themselves: the engine writes whatever
g.client_ipcarries -request.remote_addrverbatim wherever no proxy override is configured - while an administrator types the address by hand. Every path that names a row by its identifier goes through here, so only one spelling is ever stored or looked up.get_client_ip_info()is the reference: both usecanonical_client_ip(), so the blocklist and the authentication log name one client the same way. An IPv4-mapped address (::ffff:192.0.2.1) is stored as the IPv4 address it stands for (192.0.2.1), as that is the client IP of such a client.Nonerather than the value unchanged, so a caller taking an address from an administrator can refuse it (block_ip()) while one reading the table can fall back to the raw value and stay able to find - and delete - a row some other path filed under it.
- privacyidea.lib.conditional_access.engine.count_distinct_users_for_ip(source_ip: str, event_types: list[str], window_seconds: float, window_end: datetime | None = None, extra_filters: Sequence | None = None, exclude_row_ids: tuple[int, ...] | None = None) int[source]¶
Count the number of distinct accounts a single source_ip targeted with any of event_types within the sliding window
[window_end - window_seconds, window_end]. This is the password-spraying / enumeration signal: one source IP hitting many different accounts, where per-user counting never trips because each account only sees a failure or two.An account is keyed by the
(username, realm, resolver)triple - the attempted login, not the internaluid- so it counts the same for a resolved user and for an unresolved one: an attacker guessing thousands of nonexistent usernames (credential stuffing / user enumeration) is counted as thousands of distinct accounts, whereas keying on(resolver, uid, realm)would collapse every unresolved attempt into the single(NULL, NULL, NULL)identity and never trip. A request that carries no user at all (e.g. an initial usernameless passkey authentication) has aNULLusername and collapses into a single group - harmless, since those are not an account-targeting signal.Known limitation: a serial-only authentication against a token that has no user assigned also produces a
NULL-username row, so brute-forcing many such userless tokens from one IP collapses into that same single group and is not seen here. That is deliberate - there is no account being targeted: a single userless token is bounded by its own fail counter, and the many-tokens case is raw volume, left to generic rate-limiting rather than to this distinct-account signal.Unlike
count_subject_events()there is nosince_last_successreset: a successful login by one account must not clear a spraying signal aggregated across all accounts of the IP.A portable
COUNT(*)over aSELECT DISTINCTsubquery is used. TheWHEREmatchesix_authlog_ip_event_time(source_ip, event_type, timestamp) so the subquery is an index range scan; theDISTINCTover the three account columns is a cheap sort/hash over that small per-IP result set.- Parameters:
source_ip – the client IP whose distinct targeted accounts are counted
event_types – the list of
AuthEventTypevalues to count; rows matching any of them contributewindow_seconds – width of the look-back window in seconds
window_end – the instant the window ends; defaults to
utc_now(). The engine passes the single reference instant captured for the whole evaluation so this count shares it with the new block’s expiry.extra_filters – extra SQLAlchemy predicates ANDed into the
WHERE, narrowing which rows count to the ones a policy’s conditions describe (seecondition_sql_filters()).Noneor empty counts every row of the subject.exclude_row_ids – leave these row ids out, so the result is the set of accounts the other rows of the window name - the count before a request’s own rows joined it. An account that request retried is still counted through its earlier rows, so the count does not drop for it.
- Returns:
the number of distinct targeted accounts
- privacyidea.lib.conditional_access.engine.count_ip_attempts(source_ip: str, event_types: list[str], window_seconds: float, window_end: datetime | None = None, row_filter: Callable[[AuthenticationLog], bool] | None = None, exclude_row_ids: tuple[int, ...] | None = None) int[source]¶
Count whole authentication attempts (not individual
authentication_logrows) a single source_ip produced whose representative event matches event_types, within the sliding window[window_end - window_seconds, window_end]. ThePER_ATTEMPTcounterpart ofcount_ip_events(), so a multi-request challenge / multichallenge login counts once - the IP analogue ofcount_subject_attempts().As with
count_ip_events()there is nosince_last_successreset (see that function for why it is not exposed for an IP). TheWHERE(source_ip, timestamp) matches theix_authlog_ip_timeindex.- Parameters:
source_ip – the client IP whose attempts are counted
event_types – the event types an attempt’s representative must match
window_seconds – width of the look-back window in seconds
window_end – the instant the window ends; defaults to
utc_now(). An aware value is normalized to naive UTC.row_filter – an optional
(row) -> boolnarrowing the count to the attempts a policy’s conditions describe. It takes a row predicate rather than theextra_filtersSQL predicates the event counters take: the conditions must be applied to the reduced representative, never to the rows the reduction reads (see_count_attempts()).Nonecounts every attempt of the subject.exclude_row_ids – leave these row ids out of the rows fetched before the attempt reduction runs (see
_count_attempts()) - used to compute the count as it stood before the current request’s own contribution, without dropping an attempt that also has other, non-excluded rows.
- Returns:
the number of matching attempts
- privacyidea.lib.conditional_access.engine.count_ip_events(source_ip: str, event_types: list[str], window_seconds: float, window_end: datetime | None = None, extra_filters: Sequence | None = None, exclude_row_ids: tuple[int, ...] | None = None) int[source]¶
Count the
authentication_logrows a single source_ip produced with any of event_types within the sliding window[window_end - window_seconds, window_end]. This is thePER_REQUESTcounterpart ofcount_distinct_users_for_ip(): raw per-IP request volume rather than the distinct-accounts signal - the IP analogue ofcount_subject_events()keyed on the source IP instead of the subject’s own columns.Unlike the user counter there is no
since_last_successreset: a successful login by one account must not clear a volume signal aggregated across everything the IP sent (same reasoning ascount_distinct_users_for_ip()). Every matching row counts regardless of user, so userless serial attempts - the documented blind spot of the distinct-accounts signal - do contribute here.The
WHEREmatchesix_authlog_ip_event_time(source_ip, event_type, timestamp) so this is an index range scan.since_last_successis intentionally not exposed: the shared core supports it, but enabling it for an IP would reset the whole IP’s counter on any one account’s successful login (e.g. one legitimate user behind a NAT clearing the volume signal for everyone behind it) - a real semantic decision, not just wiring.- Parameters:
source_ip – the client IP whose events are counted
event_types – the list of
AuthEventTypevalues to count; rows matching any of them are counted togetherwindow_seconds – width of the look-back window in seconds
window_end – the instant the window ends; defaults to
utc_now(). An aware value is normalized to naive UTC.extra_filters – extra SQLAlchemy predicates ANDed into the
WHERE, narrowing which rows count to the ones a policy’s conditions describe (seecondition_sql_filters()).Noneor empty counts every row of the subject.exclude_row_ids – leave these row ids out of the count (see
_count_events()) - moot here since this counter never floors on a last success, but kept for the same signature every counter takes.
- Returns:
the number of matching events
- privacyidea.lib.conditional_access.engine.count_subject_attempts(subject: LockSubject, event_types: list[str], window_seconds: float, window_end: datetime | None = None, since_last_success: bool = False, row_filter: Callable[[AuthenticationLog], bool] | None = None, exclude_row_ids: tuple[int, ...] | None = None) int[source]¶
Count whole authentication attempts (not individual
authentication_logrows) for one principal whose representative event matches event_types, within a sliding time window[window_end - window_seconds, window_end]. This is thePER_ATTEMPTcounterpart ofcount_subject_events(), so a multi-request challenge / multichallenge login counts once. TheWHEREis the subject’s own columns followed bytimestamp, matchingix_authlog_user_timefor a user andix_authlog_admin_timefor a local admin.- Parameters:
subject – whose attempts are counted - a resolved user or a local database admin (see
LockSubject)event_types – the event types an attempt’s representative must match (a list; may hold a single entry)
window_seconds – width of the look-back window in seconds
window_end – the instant the window ends; defaults to
utc_now(). An aware value is normalized to naive UTC.since_last_success – only count attempts after the user’s most recent completed login in the window (a successful login resets the counter); see
_count_matching_attempts()row_filter – an optional
(row) -> boolnarrowing the count to the attempts a policy’s conditions describe. It takes a row predicate rather than theextra_filtersSQL predicates the event counters take: the conditions must be applied to the reduced representative, never to the rows the reduction reads (see_count_attempts()).Nonecounts every attempt of the subject.exclude_row_ids – leave these row ids out of the rows fetched before the attempt reduction runs (see
_count_attempts()) - used to compute the count as it stood before the current request’s own contribution, without dropping an attempt that also has other, non-excluded rows.
- Returns:
the number of matching attempts
- privacyidea.lib.conditional_access.engine.count_subject_events(subject: LockSubject, event_types: list[str], window_seconds: float, window_end: datetime | None = None, since_last_success: bool = False, extra_filters: Sequence | None = None, exclude_row_ids: tuple[int, ...] | None = None) int[source]¶
Count the
authentication_logrows for one principal and event type(s) within a sliding time window[window_end - window_seconds, window_end].event_types is a list of
AuthEventTypevalues; events matching any of them are counted together (one combined count), so a policy tracking[PASSWORD_FAIL, TOKEN_ONLY_FAIL]trips on the total of both rather than on either in isolation.The
WHEREcolumn order matches the composite index the subject’s shape is served by (seeLockSubject.log_filters) so this is an index range scan (theINover the event types still uses the same composite index).With since_last_success the count is floored at the user’s most recent completed login (
AuthEventType.LOGIN_SUCCESS) inside the window: failures that precede a successful login no longer count, so a successful authentication clears the slate. This makes the lock fire on consecutive failures since the last login rather than on every failure that happens to fall in the raw window (a legitimate user who just logged in is not re-locked by stale failures on the next single typo). The forensic log is untouched — only the counted range is narrowed.- Parameters:
subject – whose rows are counted - a resolved user or a local database admin (see
LockSubject)event_types – the list of
AuthEventTypevalues to count; rows matching any of them are counted togetherwindow_seconds – width of the look-back window in seconds
window_end – the instant the window ends; defaults to
utc_now(). An aware value is normalized to naive UTC to match the storedtimestampcolumn.since_last_success – only count events after the most recent
LOGIN_SUCCESSin the window (a successful login resets the counter)extra_filters – extra SQLAlchemy predicates ANDed into the
WHERE, narrowing which rows count to the ones a policy’s conditions describe (seecondition_sql_filters()).Noneor empty counts every row of the subject. Reaches the last-success lookup too, unlike exclude_row_ids (see_count_events()) - a condition scopes what this policy tracks, including what counts as its own reset event, where an excluded row is specifically “not counted a second time”, never “not a reset”.exclude_row_ids – leave these row ids out of the count only (see
_count_events()).
- Returns:
the number of matching events
- privacyidea.lib.conditional_access.engine.evaluate_access_decision(context: CAContext, now: datetime | None = None) AccessDecisionResult[source]¶
Pre-auth conditional-access decision for the current request: should it be denied, or left to the normal flow?
This runs before the credential check, and after the persistent
is_user_locked()/is_ip_blocked()pre-checks. It handles only theConditionalAccessAction.DENYaction; the lock/email/block actions are post-response side effects handled byevaluate_conditional_access_policies().Because there is no event for the current request yet, the decision is keyed on the user’s prior event history: for each enabled policy the events of its
counter_types_to_trackare counted (combined across all tracked types) over its window, and the matching stage with the highest threshold supplies the decision. ADENYaction therefore rejects this single request without persisting any state — a stateless, self-healing reject that lifts on its own as the failures age out of the window (contrast the durableConditionalAccessAction.LOCK_USER). With the policy’sreset_on_successthe count is floored at the user’s last completed login, so aDENYalso lifts on a successful authentication and not only with the passage of time. BecauseDENYdefaults to re-triggering, a stage withfailure_threshold0 matches every count below the next stage’s threshold, which is the lockdown idiom - scope it with conditions.Policies are evaluated by ascending
priority(a lower number means higher precedence, matching privacyIDEA’s policy engine) and the first one that denies wins, which is what decides which policy is named as having refused the request.dry_runpolicies are logged but never enforced.A subject is exempted by an applicability condition on this policy (
USER_REALM NOT_IN [...],USER_ROLE NOT_IN [...]): a policy whose conditions do not match is never evaluated for that request.Both targets can deny here: a
userpolicy is keyed on the principal the request authenticates (lock_subject()- a resolved user, or a local database admin by login name; an unknown login is neither and is never decided by a user policy), while asource_ippolicy is keyed on the context’s source IP and therefore applies even when nobody is identified at all (the spraying/enumeration case). A never-block source IP is exempt from an IPDENY, mirroring theBLOCK_IPallowlist.- Parameters:
context – what is known about the request under evaluation (see
CAContext); auserpolicy needs a principal it can key on (lock_subject()), asource_ippolicy its source IPnow – the reference time; defaults to
utc_now()
- Returns:
the
AccessDecisionResultfor this request: the decision, plus the outcomes to record on whichever authentication-log row this request ends up writing
- privacyidea.lib.conditional_access.engine.evaluate_conditional_access_policies(context: CAContext, event_type: AuthEventType | None, now: datetime | None = None) list[ConditionalAccessOutcome][source]¶
Evaluate every enabled conditional-access policy that tracks event_type and execute the actions of the triggered stage, if any. This runs post-response, after the request’s
authentication_logrow has been written (so the count includes it).Each action decides for itself whether it fires. By default an action fires once, on the evaluation that carries the failure count to at or above its stage’s threshold: an action at threshold 8 usually runs on the 8th failure and not again on the 9th, and also runs if a single step (concurrent requests, or several tracked rows staged by one request) skipped 8 outright - see
_action_fires()for the narrower race this still does not close (several such requests all committing before any of them is evaluated). An action withretrigger_above_thresholdfires on every request while the count stays within the range its stage owns - at or above threshold 8, but below the next stage’s threshold - so a single stage can email once at 8 while keeping the user locked for every further failure until the policy escalates past it (see_action_fires()and_stage_in_range()). The count climbs by one per tracked failure and, for a policy withreset_on_success, resets after a successful login (seecount_subject_events()), so a fresh burst re-triggers the fire-once actions too.Nothing is reported to the client from here. The persistent side effects (lock state) are consulted by the next inbound request via the pre-check, which reads the error message back off the row they wrote, and that is the only moment a conditional-access message is ever said. The request being evaluated has already been answered. Any error is the caller’s to swallow; this function itself only guards individual DB writes (see
_upsert_user_lock_state()).What the actions restricted is then verified against what the next request would meet, by reading the restrictions back (
_restrictions_standing()): the outcomes of a target carrying none are discarded with a warning, so a restriction that did not end up in force does not enter this request’s history. Since the request being evaluated is answered either way, that history is the only trace such a stage leaves - it must therefore not report a lock nothing is subject to. Only what a write claimed can be wrong that way; a dry-run outcome, which claims nothing, is always kept.Every action that actually ran (or, in dry run, would have run) is returned as a
ConditionalAccessOutcomefor the caller to record as this request’s history. The engine deliberately does not write them: it never sees the id of the authentication-log row they belong to.- Parameters:
context – what is known about the request under evaluation (see
CAContext);user-target policies need its user resolved,source_ip-target policies act on its source IP regardless, and theBLOCK_IPaction blocks that IPevent_type – the classified outcome of the request (
AuthEventType)now – the reference time; defaults to
utc_now()
- Returns:
the outcomes to record, one per action that ran (empty if nothing was triggered)
- privacyidea.lib.conditional_access.engine.get_ip_block(source_ip: str | None, now: datetime | None = None, *, clear_expired: bool = False) RestrictionStatus | None[source]¶
Return information about source_ip’s current block by the
BLOCK_IPaction, orNoneif the IP is not currently blocked. This is the IP counterpart ofget_user_lock()and is meant for the authentication pre-check hot path.By default this is a pure read: a row that is not enforced — its
block_expires_atlies in the past, or the IP is on the never-block allowlist — simply reads as not blocked and is left in place.With clear_expired the observed stale row is deleted on the spot, an expired timed block carries no enforced state (the authentication log is the record), so dropping it here — where the row is already loaded and known expired — cleans it up the next time that IP is seen, without a second lookup. The authentication pre-checks opt in. Permanent and still-active blocks are never deleted. The delete is defensive (see
_delete_ip_block()). A row withblock_expires_at IS NULLis a permanent block.The remaining time is surfaced so the WebUI login (
/auth) can tell the user how long the block lasts, just like the user lock (maskable via thehide_specific_error_messagepolicy); the machine-facing/validateendpoints keep the generic failure response.- Parameters:
source_ip – the client IP to check; a falsy value is never blocked
now – the reference time; defaults to
utc_now()clear_expired – delete the row if it no longer restricts anything - a stale (timed, expired) block, or any block on a never-block IP; off by default to keep this a pure read for non-auth callers
- Returns:
Noneif not blocked, else aRestrictionStatus
- privacyidea.lib.conditional_access.engine.get_subject_lock(subject: LockSubject | None, now: datetime | None = None, *, clear_expired: bool = False) RestrictionStatus | None[source]¶
Return information about subject’s current lock, or
Noneif they are not currently locked. Intended for the authentication pre-check hot path.By default this is a pure read: a stale row whose
lock_expires_atlies in the past simply reads as not locked and is left in place.With clear_expired the observed stale row is deleted on the spot. An expired timed lock carries no enforced state — it already reads as not locked and the authentication log is the historical record — so dropping it here, where the row is already loaded and known expired, cleans it up on the user’s next login without a second lookup. The authentication pre-checks opt in; nothing that merely inspects a user’s status does. Permanent and still-active locks are never deleted. The delete is defensive (see
_delete_user_lock_state()).A row with
lock_expires_at IS NULLis a permanent lock.- Parameters:
subject – the principal to check;
None(nobody this could be keyed on, e.g. an unknown login) is never lockednow – the reference time; defaults to
utc_now()clear_expired – delete the row if it is a stale (timed, expired) lock; off by default to keep this a pure read for non-auth callers
- Returns:
Noneif not locked, else aRestrictionStatus
- privacyidea.lib.conditional_access.engine.get_user_lock(user: User, now: datetime | None = None, *, clear_expired: bool = False) RestrictionStatus | None[source]¶
get_subject_lock()for a caller holding aUser- the management layer and everything that looks a user up by hand. An unresolved user is never locked, which is whatLockSubject.for_user()answersNonefor; a local admin is not reachable this way at all, having no user object to be passed in (seelock_subject()).
- privacyidea.lib.conditional_access.engine.get_user_lock_by_login(login: str | None, now: datetime | None = None, *, clear_expired: bool = False) RestrictionStatus | None[source]¶
The lock standing on a user whose login name is login, in whichever realm, or
Noneif no such user is locked. Keyed on the name alone, deliberately: this answers a question asked before a request has an identity./authaccepts a bare login name and only finds out which principal it named by seeing which credential matches - a local database admin’s, or a same-named user’s in the default realm (see_evaluate_rejection(), the one caller). The pre-check runs before that, so it cannot ask “is this principal locked” without guessing which one; it asks “is any principal this name could mean locked” instead, and this is the half of that question a user’s row answers. Only rows a user left are matched - a local admin’s row is reached by its own key, which is exact.Several realms can hold a user of one name, and any of their locks bars a login under the bare name, so the first one standing is returned. A row is not narrowed to the default realm because the realm this request would have resolved to is not settled at this point (
get_realm_for_authenticationmay rewrite it), and refusing too widely here is a refusal, never an admission - as long as the principal being refused is one the operator meant to be lockable at all, which is the caller’s to establish (seecan_be_locked()).
- privacyidea.lib.conditional_access.engine.is_ip_blocked(source_ip: str | None, now: datetime | None = None, *, clear_expired: bool = False) bool[source]¶
Return whether source_ip is currently blocked by the
BLOCK_IPaction. Thin boolean wrapper overget_ip_block()for the authentication pre-check hot path; see that function for the expiry, permanent-block, and clear_expired semantics.- Parameters:
source_ip – the client IP to check; a falsy value is never blocked
now – the reference time; defaults to
utc_now()clear_expired – delete the row if it is a stale (timed, expired) block or a block on a never-block IP
- Returns:
Trueif the IP is currently blocked
- privacyidea.lib.conditional_access.engine.is_ip_never_block(source_ip: str | None) bool[source]¶
Return whether source_ip must never be blocked by the conditional-access engine: it is loopback (built-in) or matches the
PI_CONDITIONAL_ACCESS_NEVER_BLOCKallowlist from the server configuration. A falsy or unparsable IP is treated as never-block as well — fail safe: never block an address the engine cannot positively identify.An IPv4-mapped address is checked in both forms, because a network of one family never contains an address of the other: a dual-stack listener puts an IPv4 client in
REMOTE_ADDRas::ffff:192.0.2.1, and comparing only that form matches neither the built-in127.0.0.0/8nor an allowlisted IPv4 proxy or NAT range — the whole allowlist would be off for those deployments, which is the one direction this guard must never fail in.Only the mapped form is unwrapped, not the 6to4 or Teredo encodings
ipaddressalso recognizes: a mapped address is how the operating system renders a real IPv4 peer, while a tunnel address is chosen by the client, and unwrapping one would let a client encode an allowlisted address to make itself unblockable.
- privacyidea.lib.conditional_access.engine.is_user_locked(user: User, now: datetime | None = None, *, clear_expired: bool = False) bool[source]¶
Return whether user is currently locked. Thin boolean wrapper over
get_user_lock()for the authentication pre-check hot path; seeget_subject_lock()for the expiry, permanent-lock, and clear_expired semantics.- Parameters:
user – the user to check; an unresolved user is never locked
now – the reference time; defaults to
utc_now()clear_expired – delete the row if it is a stale (timed, expired) lock
- Returns:
Trueif the user is currently locked
- privacyidea.lib.conditional_access.engine.lock_subject(context: CAContext) LockSubject | None[source]¶
The principal context describes for counting and locking, or
Nonewhen it describes none auser-target policy could act on.The resolved user comes first, and a local admin only where the request says the principal is one: the role, which
/authverified (or, pre-auth, resolved from the name it was given), never the mere presence of a login name. Every request carries one of those, the unknown logins that must stay uncountable here included.
- privacyidea.lib.conditional_access.engine.parse_lock_duration_seconds(action_value: Any) int | None[source]¶
Parse the
LOCK_USER/BLOCK_IPrestriction duration (in seconds) from a stage action’s JSONaction_value. Accepts a plain integer, a numeric string, or a dict carryingduration_seconds/duration. ReturnsNonefor anything that is not a positive integer of at mostMAX_LOCK_DURATION_SECONDSseconds.This is also the write path’s validator (
_validate_duration_action_value()), so what can be stored and what the engine can act on are the same set by construction rather than by two descriptions agreeing.
- privacyidea.lib.conditional_access.engine.rank_and_deduplicate(messages: list[StageMessage]) list[StageMessage][source]¶
The messages to show, ordered by
ACTION_SEVERITYand with each distinct sentence kept once.Ranked before de-duplicating, so where the same sentence stands on a user lock and on a source-IP block, the copy kept is the one labelled with the severer action - and a reader of the result sees the ranking the restriction earned. The sort is stable, so messages of equal severity stay in the order they were collected in. A message about an action with no rank sorts last, so an oversight in
ACTION_SEVERITYcosts the order rather than the message.
- privacyidea.lib.conditional_access.engine.render_error_message(error_message: str | None, restriction: RestrictionStatus | None = None) str | None[source]¶
The user-facing text for error_message, or
Nonewhen there is none and the caller should stay generic.{duration}only means something where there is a remaining time, so it is substituted only against a timed restriction. Everywhere else - a permanent lock or block, aDENY, a stage that merely notified - it is left exactly as written, like any other tag we do not substitute. That is a misconfiguration rather than a case to handle: a countdown was written for something that does not count down.A plain string replacement, not
_safe_format(): with a single tag there is nothing to parse, a stray brace in the admin’s prose cannot make the substitution fail (format_mapwould raise on a bare{}and return the template untouched, silently dropping the duration), and no attribute traversal is reachable from admin-supplied text.Call this only when the request is actually being turned away. An expired or absent lock is not a rejection at all - there is nothing to tell the user - so passing
Noneto mean “not locked” would log a missing duration for a login that is about to succeed.- Parameters:
error_message – the stored template, or
Nonerestriction – the restriction in force, when there is one;
Nonefor a decision or a notification, which turn a request away without leaving anything behind
- privacyidea.lib.conditional_access.engine.restriction_messages(*restrictions: RestrictionStatus | None, use_default_error_message: bool = False) list[StageMessage][source]¶
The error message of each of restrictions that carries any, ranked and de-duplicated.
Silent by default: a restriction carrying no error message produces none, and
None(nothing in force) contributes nothing at all. With use_default_error_message the wording for the restriction’s shape stands in for a missing one, which is what theshow_default_ca_error_messagepolicy buys - an admin gets the same sentence they would have got by writing the suggestion onto every stage by hand. Silent is not the same as generic: producing no message is what leaves a rejection indistinguishable from any other failure, and what the response then says instead is the caller’s question to answer.Called only by the pre-check that refuses a restricted request (
_evaluate_rejection()): a restriction is described from the row in force, on the requests it actually refuses, and never by the evaluation that wrote it.
17.2.1.5.6. Conditional access policies¶
CRUD layer for conditional-access policies.
The engine (privacyidea.lib.conditional_access.engine) only reads
ConditionalAccessPolicy rows; this module is
the write path used by the REST API (/conditionalaccess) and anything else
that needs to create, edit or delete policies. All input validation lives
here, so the API layer stays a thin request/response wrapper.
A policy is passed around as a plain dict:
{
"name": "Brute Force Lock",
"time_window_seconds": 600,
"enabled": True,
"dry_run": False,
"priority": 1,
"target": "user",
"count_mode": "PER_REQUEST",
"reset_on_success": True,
"counter_types_to_track": ["PIN_FAIL", "MFA_FAIL"],
"conditions": [
{"condition_type": "USER_REALM", "operator": "IN", "value": ["sales", "support"]},
],
"stages": [
{
"failure_threshold": 5,
"error_message": "Your account is locked. Please try again in about {duration}.",
"actions": [
{"action_type": "LOCK_USER", "action_value": {"duration_seconds": 600},
"retrigger_above_threshold": True},
{"action_type": "EMAIL_ADMIN",
"action_value": {"smtp_identifier": "mailserver", "subject": "...", "body": "..."},
"retrigger_above_threshold": False},
],
},
],
}
count_mode is a CountMode name whose valid
values depend on the target (see _COUNT_MODES_BY_TARGET): both targets count event volume per authentication_log
row (PER_REQUEST) or per whole authentication attempt (PER_ATTEMPT); a source_ip policy may additionally
count distinct targeted accounts (DISTINCT_USERS, the spraying / enumeration signal). When omitted it defaults to
the target’s default (PER_REQUEST for user, DISTINCT_USERS for source_ip).
reset_on_success (default True) decides whether a completed login clears the events counted so far, so the
stage thresholds apply to consecutive failures since that login rather than to every failure in the raw window.
Turning it off is how a threshold comes to mean “this many failures in the window” outright. It governs every count
the policy makes, the pre-auth DENY decision included. It applies to a user policy only: a
source_ip policy aggregates a signal across accounts, where one account’s legitimate login must not clear it, so
setting it on a source_ip policy is a ParameterError rather than an ignored
setting (the default there is False).
counter_types_to_track
values must be
AuthEventType names and action_type values
must be ConditionalAccessAction names; anything else is a
ParameterError (fail-closed - a typo must not silently create a policy that never
matches or an action that never fires). Within one stage an action may appear only once - except
EMAIL_ADMIN/EMAIL_USER (REPEATABLE_ACTIONS), where a second copy is how one stage notifies a
second set of recipients - and no stage may hold two actions of the same mutually exclusive group
(_EXCLUSIVE_ACTION_GROUPS: timed vs permanent lock, timed vs permanent block).
action_value is validated under that same rule, against what the engine actually reads (see
_ACTION_VALUE_VALIDATORS):
LOCK_USER/BLOCK_IP- a positive number of seconds: an integer, a numeric string, or an object withduration_seconds(durationis an accepted alias). There is no default; without a duration the engine skips the action rather than locking permanently.EMAIL_ADMIN/EMAIL_USER- an object with a non-emptysubjectandbody, optionallymimetype(plain/html) and - forEMAIL_ADMIN-recipient_group.smtp_identifiernames the SMTP server that sends it and may be left blank until one is configured, which is the one thing the engine needs that the write path does not insist on.PERMANENT_LOCK_USER/PERMANENT_BLOCK_IP/DENY- no value. These never expire and never read one, so a duration on them would only describe an expiry that does not happen.
A stage’s optional error_message is the text an end user sees on a request that a lock, a block or a DENY
from that stage turns away - never on the request that trips the stage, which has already been answered on its own
merits. A stage that only notifies turns no request away and can therefore never show one at all, whatever is
written on it. It is opt-in: without one the rejection carries only the generic “Authentication failed.”, so
privacyIDEA never volunteers that an account is locked or an IP blocked unless an admin chose to say so - either by
writing this field, or by setting the show_default_ca_error_message policy, which fills in the default wording
for the stage’s actions (DEFAULT_ERROR_MESSAGES). {duration} is substituted with the remaining
time at rejection, and only where there is one: on a permanent lock or a DENY it is left as written, like any
other tag that is not substituted. Every other brace expression is left exactly
as written - braces in prose need no escaping - so only the length is validated here.
conditions is the applicability axis, orthogonal to the counting one: it restricts which requests the policy
applies to at all, while the counter types and thresholds decide what trips it. It is optional - a policy without
conditions applies to every request - and is validated against the registries in
conditions under the same fail-closed rule, since a condition naming an
unknown realm or a misspelled role would otherwise silently never match.
- class privacyidea.lib.conditional_access.policy.ConditionDefinition(condition_type: str, operator: str, value: list[str])[source]¶
One validated applicability condition (see
_validate_conditions()).- condition_type: str¶
- operator: str¶
- value: list[str]¶
- privacyidea.lib.conditional_access.policy.DECISION_ACTIONS = frozenset({ConditionalAccessAction.DENY})¶
The actions that state a standing pre-auth verdict rather than reacting to a count. They default to re-triggering, and a stage carrying only these may use threshold 0.
- privacyidea.lib.conditional_access.policy.DEFAULT_ERROR_MESSAGES: dict[str, object] = {ConditionalAccessAction.BLOCK_IP: l'Access from your IP address is temporarily blocked. Please try again in about {duration}.', ConditionalAccessAction.DENY: l'Access has been denied.', ConditionalAccessAction.LOCK_USER: l'Your account is temporarily locked. Please try again in about {duration}.', ConditionalAccessAction.PERMANENT_BLOCK_IP: l'Access from your IP address has been blocked. Please contact your administrator.', ConditionalAccessAction.PERMANENT_LOCK_USER: l'Your account has been locked. Please contact your administrator.'}¶
The default user-facing wording per action: what the policy editor suggests, and what the
show_default_ca_error_messagepolicy falls back to for a stage that wrote none.
- privacyidea.lib.conditional_access.policy.MAX_COLUMN_INT = 2147483647¶
The largest value a field stored in an
Integercolumn may take: the signed 32-bit ceiling, which MySQL and PostgreSQL enforce and SQLite does not.
- privacyidea.lib.conditional_access.policy.MAX_PRIORITY = 1000000¶
The largest priority a policy may carry, deliberately far below
MAX_COLUMN_INT. Reordering parks the rows it moves above the highest live priority (seereorder_conditional_access_policies()), so the room between this and the column ceiling is that parking space - over two thousand times more than the number of policies any installation would reorder at once. A priority is a position in an ordering, not a quantity; nothing needs seven digits of it.
- privacyidea.lib.conditional_access.policy.REPEATABLE_ACTIONS = frozenset({ConditionalAccessAction.EMAIL_ADMIN, ConditionalAccessAction.EMAIL_USER})¶
The actions a stage may carry more than once - the notifications, where a second copy reaches a different set of recipients.
- class privacyidea.lib.conditional_access.policy.StageActionDefinition(action_type: str, action_value: object = None, retrigger_above_threshold: bool | None = None)[source]¶
One validated stage action (see
_validate_stages()).retrigger_above_thresholdleft atNonemeans “not chosen”: it is resolved to the action-aware default in_build_stages()(re-trigger for theDECISION_ACTIONS, fire-once for the post-response effects).- action_type: str¶
- action_value: object = None¶
- retrigger_above_threshold: bool | None = None¶
- class privacyidea.lib.conditional_access.policy.StageDefinition(failure_threshold: int, actions: list[~privacyidea.lib.conditional_access.policy.StageActionDefinition] = <factory>, name: str | None = None, error_message: str | None = None)[source]¶
One validated stage with its actions, as produced by
_validate_stages()and consumed by_build_stages(). Using a dataclass (instead of a baredict) makes the shape explicit and lets the type checker verify the hand-off between validation and ORM building.- actions: list[StageActionDefinition]¶
- error_message: str | None = None¶
- failure_threshold: int¶
- name: str | None = None¶
- privacyidea.lib.conditional_access.policy.conditional_access_policy_to_dict(policy: ConditionalAccessPolicy) dict[source]¶
Serialize a
ConditionalAccessPolicywith its stages and actions into the plain-dict shape documented in the module docstring (plus theidof each row).
- privacyidea.lib.conditional_access.policy.create_conditional_access_policy(name: str, time_window_seconds: int, counter_types_to_track: list[str], stages: list[dict], target: str, priority: int, enabled: bool = True, dry_run: bool = False, reset_on_success: bool | None = None, count_mode: str | None = None, conditions: list[dict] | None = None) int[source]¶
Create a conditional-access policy with its stages and actions in one transaction.
See the module docstring for the parameter shapes; everything is validated here and a
ParameterErroris raised on any invalid input before anything is written.targetis required (no silent default) so the target/action compatibility is always a deliberate choice.priorityis likewise required (no default) and must be unique across policies, so the caller always picks a deliberate, unambiguous precedence.count_modeandreset_on_successdefault to the target’s default when not given (see_validate_count_mode()and_validate_reset_on_success()).conditionsrestricts which requests the policy applies to; omitted (or empty) it applies to every request.- Returns:
the id of the new policy
- privacyidea.lib.conditional_access.policy.default_error_message(action: str) str | None[source]¶
The default error message for action, translated against the request locale, or
Nonewhere it has none.Nonecovers any action without error message - one that turns nobody away, or one added later - so a caller falling back to this never has to know which actions are covered.
- privacyidea.lib.conditional_access.policy.delete_conditional_access_policy(policy_id: int) int[source]¶
Delete a conditional-access policy with all its stages and actions.
Existing locks/blocks written by this policy stay in force: live state is independent of the policy config.
- Returns:
the id of the deleted policy
- Raises:
ResourceNotFoundError – if no policy with this id exists
- privacyidea.lib.conditional_access.policy.enable_conditional_access_policy(policy_id: int, enable: bool = True) int[source]¶
Enable or disable a conditional-access policy.
- Returns:
the id of the policy
- Raises:
ResourceNotFoundError – if no policy with this id exists
- privacyidea.lib.conditional_access.policy.get_conditional_access_policy(policy_id: int) dict[source]¶
Return one conditional-access policy as a dict.
- Raises:
ResourceNotFoundError – if no policy with this id exists
- privacyidea.lib.conditional_access.policy.get_default_error_messages() list[dict[str, str]][source]¶
The suggested stage error messages, ordered by
ACTION_SEVERITY, as[{"action_type": ..., "message": ...}]. Translated on each call against the request locale.An authoring aid for the policy editor, which composes one suggestion for a stage carrying several actions: one sentence per action, kept in this order.
Only actions that describe a standing state are in here - a restriction in force, or a denial - because those are the only ones anything can report: a message is said by the pre-check refusing a restricted request, off the row in force, and a row records what is in force rather than the notifications a stage also sent. So a notify-only stage gets no suggestion, its wording having nowhere to be shown.
That the two sets coincide today is not something to build on: this answers “which actions have a default sentence”, and
REPORTING_ACTIONS- served per target byget_target_constraints()- answers which actions can report at all. Adding or dropping a suggestion here must not change what anything believes about the second.The same table backs the runtime fallback under
show_default_ca_error_message(default_error_message()), so an admin who edits a suggestion is editing the thing they would otherwise have got by default.Deliberately not scoped by target: the binding is action to message, and a client picks the entry whose action the stage actually carries, so error message for an action a target cannot hold simply never matches.
- privacyidea.lib.conditional_access.policy.get_target_constraints() dict[str, dict[str, list]][source]¶
The per-target policy constraints, as
{target_value: {"actions": [...], "count_modes": [...], "repeatable_actions": [...], "exclusive_action_groups": [[...], ...], "reporting_actions": [...]}}: for each target the stage actions it allows (_ACTIONS_BY_TARGET), the count modes it supports (_COUNT_MODES_BY_TARGET), which of its actions may appear more than once in one stage (REPEATABLE_ACTIONS), which of its actions contradict each other within one stage (_EXCLUSIVE_ACTION_GROUPS) and which of them a request can ever be told about (REPORTING_ACTIONS), all sorted.Everything but the first two is served rather than left for the client to hard-code, for the same reason the condition-type registry is: a rule the editor enforces should come from the one place that defines it. In particular the editor warns that a stage’s wording can never be shown, which is a question about what its actions do - not about which actions happen to have default wording to suggest, a table it would otherwise have to infer this from (see
get_default_error_messages()).All three are filtered to the actions the target allows, so a rule that cannot arise for this target (the lock pair under
source_ip, the block pair underuser) is not offered as one the editor could never apply.
- privacyidea.lib.conditional_access.policy.list_conditional_access_policies(enabled: bool | None = None) list[dict][source]¶
Return all conditional-access policies as dicts, lowest priority number first (the engine’s evaluation order: a lower number means higher precedence, matching privacyIDEA’s policy engine).
- Parameters:
enabled – if given, only return policies with this enabled state
- privacyidea.lib.conditional_access.policy.reorder_conditional_access_policies(policy_ids: list[int], expected_priorities: list[int] | None = None) None[source]¶
Rearrange the evaluation order of the given policies.
The listed policies take the priority values that this very set of policies already holds, in ascending order: the first id gets the lowest of those values (highest precedence), the last id the highest. Only the ownership of the values changes, so the set of priorities in the table is an invariant. That is what makes this safe whatever numbering the admin uses - contiguous
1,2,3reorders exactly like gapped10,20,30, nothing is renumbered, no value is ever exhausted and the uniqueness constraint is never strained.Any subset may be passed, and policies not listed keep their priority. Only the policies that actually move need to be sent: the rows whose position changes are the permutation’s support, which is a union of cycles, so the values they collectively hold are the same before and after - sending just them yields exactly the same result as sending everything. A single swap is therefore two ids, and two admins rearranging disjoint parts of the list do not conflict at all. Passing an already-sorted order is a no-op, which makes the operation idempotent.
expected_priorities is an optional per-id assertion, aligned with policy_ids: the priority each policy is expected to hold right now. It turns a concurrent rearrangement from a silent overwrite into a clean
ConflictError, and because it covers only the submitted policies it fires solely when someone changed a row this caller is about to move.- Parameters:
policy_ids – the policies to rearrange, in the wanted evaluation order
expected_priorities – the priorities the caller last saw for those policies, in the same order; omit to write unconditionally
- Raises:
ParameterError – if policy_ids is not a list of distinct ids, or the assertion does not line up with it
ResourceNotFoundError – if any id does not exist
ConflictError – if a policy no longer holds its asserted priority
- privacyidea.lib.conditional_access.policy.update_conditional_access_policy(policy_id: int, name: str | None = None, time_window_seconds: int | None = None, counter_types_to_track: list[str] | None = None, stages: list[dict] | None = None, enabled: bool | None = None, dry_run: bool | None = None, reset_on_success: bool | None = None, priority: int | None = None, target: str | None = None, count_mode: str | None = None, conditions: list[dict] | None = None, reset_counters_on_enforce: bool = True) tuple[int, list[str]][source]¶
Update a conditional-access policy. Only the given (non-
None) fields are changed.counter_types_to_track,stagesandconditionsare replaced as a whole when given - the delete-orphan cascade drops the previous child rows. Passing an emptyconditionslist therefore removes every condition, which widens the policy to apply to all requests. Locks and blocks this policy has already written stay in force: live state is independent of the policy config.targetmay be changed, but the resulting(target, stages)combination must stay action-compatible (e.g. asource_ippolicy cannot carryLOCK_USER); an incompatible change raisesParameterError. The same holds for(target, count_mode).reset_on_successis likewise target-bound: asking for it on asource_ippolicy is aParameterError, while switching an existing resetting policy to that target clears the flag (and reports it as changed), since the policy no longer resets. Existing locks/blocks written before the change are timed and expire on their own, so no stale state is left enforced.Turning
dry_runoff (True->False) setsenforced_sinceto now, so the count functions floor their look-back window there and the policy is judged only on events from this point on, not on whatever accumulated before - seeenforced_since. Passreset_counters_on_enforce=Falseto clear the floor instead and count the policy’s full time window from the first enforced request on (e.g. an admin who ran the dry run specifically to see how many people would already be caught). Mind that a count which already sits above a stage’s threshold never reaches it, so that stage stays silent until the old events age out of the window. This has no effect unlessdry_runis also being turned off in this same call. Turningdry_runon leavesenforced_sinceuntouched: the trial simulates the enforcement it interrupted, floor included.All fields are validated before anything is written. Only the fields the caller sends are validated, which is what keeps a policy stored before a validation rule existed - or written straight through the ORM - from being frozen: its
enabled/dry_runflags and its name stay changeable, and re-sendingstagesis the repair path that re-checks them.- Returns:
a
(policy_id, changed_fields)tuple, wherechanged_fieldsis the list of field names that were provided (and thus written), so the caller can record them in the audit log- Raises:
ResourceNotFoundError – if no policy with this id exists
- privacyidea.lib.conditional_access.policy.validate_error_message(error_message: str | None) str | None[source]¶
Validate an optional user-facing error message - the text surfaced to the end user when a request is turned away.
Noneor an empty/blank string means “say nothing” and returnsNone, which is the default: a rejection reveals no conditional-access detail unless an admin writes it here.Only the length is checked. Brace expressions are deliberately not validated:
{duration}is the one tag substituted at rejection time and everything else -{},{whatever}- is left literal, so an admin can write braces in ordinary prose without escaping them. The WebUI hints at an unrecognized tag; it is not an error here.
17.2.1.5.7. Policy conditions¶
Which requests a conditional-access policy applies to.
This is the applicability axis of a policy, orthogonal to the counting one: the conditions here decide whether a policy is evaluated for a request at all, while the policy’s counter types, count mode and stage thresholds decide what trips it. Keeping them separate is what lets the two compose - a policy can restrict itself to a realm and still require a threshold of failures.
A condition is a triple of what to read (condition_type), how to compare
(operator) and what to compare against (value), evaluated against the
CAContext of the current
request. Two registries define the vocabulary:
CONDITION_TYPES- oneConditionTypeSpecper readable value, declaring how to resolve it from the context and which operators it permits.OPERATORS- oneOperatorSpecper comparison, including what that comparison means when the request carries no value.
Adding a condition kind is therefore a registry entry, not a schema change.
All of a policy’s conditions must hold (AND). A policy with no conditions applies to everyone, which is why introducing them leaves existing policies behaving exactly as before.
Missing values follow from the operator, by treating an absent value as one
that belongs to no set: IN does not match it, NOT_IN does. This is not
configurable, and deliberately so - it is the only reading that keeps an
exemption honest. Consider an anti-enumeration policy on a source IP carrying
USER_REALM NOT_IN [sales] to spare one realm: the requests it exists to stop
probe non-existent usernames, which resolve to no realm at all. Were a missing
value to make the condition fail, the exemption would swallow exactly the traffic
the policy was written for. Treating “no realm” as “not sales” keeps it applying.
That one rule governs both things a condition does, so they can never contradict each other - but note they ask it about different subjects:
operator |
gate: the request carries no value |
count: a log row’s column is NULL |
|---|---|---|
|
no match - the policy does not apply |
row is not counted |
|
matches - the policy applies |
row is counted |
OperatorSpec.matches_missing states it for the gate and
OperatorSpec.sql for the count; the second needs the null case spelled out
because SQL’s three-valued logic makes col NOT IN (...) false for NULL,
which would have inverted the exemption in the query relative to Python. So a
request the gate admits is one whose rows the filter admits - what differs is only
that the gate reads one value (this request’s) while the filter reads each row’s.
Nothing here raises. This runs on the authentication hot path, pre-auth and post-response, and the engine is built so that conditional access can never break an authentication. An unknown condition type, an unknown operator, or a failing resolver is logged and treated as not matching, i.e. the policy does not apply. That is the conservative reading of “this policy carries a restriction I cannot evaluate”: a policy is never applied on the strength of a condition that could not be checked.
- privacyidea.lib.conditional_access.conditions.CONDITION_TYPES: dict[str, ConditionTypeSpec] = {ConditionType.ENDPOINT: ConditionTypeSpec(name=<ConditionType.ENDPOINT: 'ENDPOINT'>, label=l'Endpoint', operators=frozenset({<ConditionOperator.NOT_IN: 'NOT_IN'>, <ConditionOperator.IN: 'IN'>}), resolve=<function _resolve_endpoint>, choices=<function <lambda>>, log_column=<sqlalchemy.orm.attributes.InstrumentedAttribute object>), ConditionType.USER_REALM: ConditionTypeSpec(name=<ConditionType.USER_REALM: 'USER_REALM'>, label=l'User realm', operators=frozenset({<ConditionOperator.NOT_IN: 'NOT_IN'>, <ConditionOperator.IN: 'IN'>}), resolve=<function _resolve_user_realm>, choices=<function _realm_choices>, log_column=<sqlalchemy.orm.attributes.InstrumentedAttribute object>), ConditionType.USER_ROLE: ConditionTypeSpec(name=<ConditionType.USER_ROLE: 'USER_ROLE'>, label=l'User role', operators=frozenset({<ConditionOperator.NOT_IN: 'NOT_IN'>, <ConditionOperator.IN: 'IN'>}), resolve=<function _resolve_user_role>, choices=<function <lambda>>, log_column=<sqlalchemy.orm.attributes.InstrumentedAttribute object>)}¶
The condition types a policy may apply, keyed by
ConditionType: the request attribute each reads, the operators it permits and its currently valid values.
- class privacyidea.lib.conditional_access.conditions.ConditionOperator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
How a condition compares the value read from the request against the value stored on the condition.
Only set membership exists for now, which is deliberate rather than provisional: every condition type currently defined reads from a closed, enumerable vocabulary (realm names, roles, endpoints), where a multi-select of known values beats a free-text comparator - it cannot be typo’d into a condition that silently never matches. Scalar comparison operators (equality, regex) earn their place when a condition type with an open value space arrives, and should then delegate to
compare_values()rather than reimplement its regex and date handling.The names mirror that module’s
in/!incomparators, so the product speaks one vocabulary; the implementation differs becausecompare_valuesexpects its right-hand side as a comma-separated string, whereas a condition stores a JSON list.stris used instead ofStrEnum(3.11+) for compatibility with Python 3.10, mirroringAuthEventType.- IN = 'IN'¶
- NOT_IN = 'NOT_IN'¶
- class privacyidea.lib.conditional_access.conditions.ConditionType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
The condition types shipped today. See
CONDITION_TYPESfor their specs.- ENDPOINT = 'ENDPOINT'¶
- USER_REALM = 'USER_REALM'¶
- USER_ROLE = 'USER_ROLE'¶
- class privacyidea.lib.conditional_access.conditions.ConditionTypeSpec(name: str, label: object, operators: frozenset[str], resolve: Callable[[CAContext], Any], choices: Callable[[], list[str]] | None = None, log_column: Any | None = None)[source]¶
One value a condition can read from the request, and everything needed to evaluate, validate and display a condition on it.
- Variables:
name – the stored
condition_typevaluelabel – a
lazy_gettextstring naming the condition for the editoroperators – the operators this type permits. Restricting them per type is what keeps a nonsensical pairing from ever being offered.
choices – the currently valid values, for the editor’s selection list and for write-time validation. Called per request rather than captured, because the vocabulary changes as realms are created and deleted.
Nonefor a type whose values cannot be enumerated.resolve –
(context) -> value | None- reads this type’s value from the request context, returningNonewhen the request carries no usable value. There is no separate “absent” sentinel because there is nothing to distinguish it from: the request always carries a user object (an empty one when nothing resolved), so an unknown realm arrives as an empty string, not as an absent attribute - and both mean the same thing here. A future type whose value is legitimately falsy (a boolean) must returnFalserather than collapsing it, since the check below isis Noneand not a truthiness test. What aNonethen means is the operator’s call, not the type’s - seeOperatorSpec.matches_missing.log_column – the
authentication_logcolumn holding the same value this type reads from the request, orNonewhen there is none. It is what lets a condition scope the counting query and not just gate the request (seecondition_sql_filters()); a type without one stays gate-only, which is the right default for a value the log does not record since a predicate cannot be written for it at all.
- choices: Callable[[], list[str]] | None = None¶
- label: object¶
- log_column: Any | None = None¶
- name: str¶
- operators: frozenset[str]¶
- privacyidea.lib.conditional_access.conditions.OPERATORS: dict[str, OperatorSpec] = {ConditionOperator.IN: OperatorSpec(name=<ConditionOperator.IN: 'IN'>, label=l'is one of', apply=<function <lambda>>, matches_missing=False, sql=<function <lambda>>), ConditionOperator.NOT_IN: OperatorSpec(name=<ConditionOperator.NOT_IN: 'NOT_IN'>, label=l'is not one of', apply=<function <lambda>>, matches_missing=True, sql=<function <lambda>>)}¶
The condition operators, keyed by
ConditionOperator: how each one matches in Python and in SQL, and whether it matches a request carrying no value.
- class privacyidea.lib.conditional_access.conditions.OperatorSpec(name: str, label: object, apply: Callable[[Any, Any], bool], matches_missing: bool, sql: Callable[[Any, list[str]], Any])[source]¶
One comparison a condition can use.
- Variables:
name – the stored
ConditionOperatorvaluelabel – a
lazy_gettextstring naming the operator for the editorapply –
(actual, values) -> bool, where actual is the value read from the request and values the stored listmatches_missing – what this operator yields when the request carries no value at all. It follows from the operator rather than being configured, by treating a missing value as one that belongs to no set: it is in nothing (
IN-> False) and it is not in anything (NOT_IN-> True). See the module docstring for why that is also the safe reading.sql –
(column, values) -> ColumnElement- the same comparison as a SQL predicate, for scoping the counting query (seecondition_sql_filters()). It must agree withmatches_missingon aNULLcolumn, which SQL does not give for free:col NOT IN (...)is false forNULLunder three-valued logic, soNOT_INhas to spell the null case out or the exemption would silently invert in SQL relative to Python.
- apply: Callable[[Any, Any], bool]¶
- label: object¶
- matches_missing: bool¶
- name: str¶
- sql: Callable[[Any, list[str]], Any]¶
- privacyidea.lib.conditional_access.conditions.condition_matches(condition: ConditionalAccessPolicyCondition, context: CAContext, policy_name: str = '') bool[source]¶
Whether a single condition holds for context.
An unknown condition type or operator, or a resolver that raises, yields
False(the policy does not apply) and is logged - see the module docstring for why this never raises. A value the request does not carry is answered byOperatorSpec.matches_missing, so the admin reasons about the operator they picked rather than a per-type rule they cannot see.- Parameters:
condition – the stored condition row
context – what is known about the request under evaluation
policy_name – the owning policy’s name, for log messages only
- Returns:
True if the condition holds
- privacyidea.lib.conditional_access.conditions.condition_sql_filters(policy: ConditionalAccessPolicy) list[source]¶
The policy’s conditions as SQL predicates on
authentication_log, for narrowing which rows a count considers.This is the counting half of a condition, applied in addition to - never instead of - the applicability half (
policy_matches_context()). The two ask the same question of different subjects: gating asks it of the request in front of us, scoping asks it of each row of the subject’s history. Both use the one missing-value rule, so they cannot disagree (see the module docstring).It is what a
source_ippolicy needs to count what its admin asked for: the subject is the IP, whose rows span many identities, realms and roles, so without a filter a narrowly scoped policy would still count the IP’s entire history. For auserpolicy the predicates are redundant - the subject pins the realm, and with it the role - but harmless, which is why there is one rule for both.Only call this when
policy_conditions_are_scopable()is true. A condition without alog_columnis logged and skipped here rather than silently widening the count, but relying on that would count rows the admin excluded.- Parameters:
policy – the policy whose conditions are translated; its
conditionsrelationship is read, nothing is written- Returns:
one SQLAlchemy predicate per condition, to be ANDed into the counting query’s
WHERE. Empty when the policy has no conditions, or when none of them can be expressed against the log.
- privacyidea.lib.conditional_access.conditions.conditions_match_row(policy: ConditionalAccessPolicy, row) bool[source]¶
Whether every condition of policy holds for a single
authentication_logrow.The row counterpart of
policy_matches_context(), and the third place the same question is asked (gate: the request; scope: the counted rows). It exists forPER_ATTEMPTcounting, which cannot use the SQL predicates ofcondition_sql_filters(): that counter reduces all rows sharing anattempt_idto the one event that classifies the attempt, and aWHEREclause filters rows before the reduction sees them. Dropping one row of an attempt corrupts the reduction rather than narrowing it - most sharply when the dropped row is theLOGIN_SUCCESSthat should have superseded the attempt’s failures, which then counts as a failure. Applying the conditions to the reduced outcome row instead leaves the reduction whole and asks the question once, of the row that actually classifies the attempt.Each condition reads its own
ConditionTypeSpec.log_columnoff the row, so this is theapply/matches_missingpaircondition_matches()uses - not thesqlpair. That is whyNOT_INneeds no null-handling here: the missing-value rule is the operator’s, applied directly, rather than something SQL’s three-valued logic has to be talked into agreeing with.Fails closed like its siblings: an unknown type/operator, a type without a
log_column, or a raising comparison yieldsFalse(the row does not count) and is logged, never raises. A policy with no conditions matches every row.- Parameters:
policy – the policy whose conditions are evaluated; only
conditionsis readrow – the
AuthenticationLogrow to test
- Returns:
True if every condition holds for the row
- privacyidea.lib.conditional_access.conditions.get_condition_types() dict[str, dict][source]¶
Describe every available condition type, so the policy editor is built from server metadata instead of a hard-coded client-side list (mirroring
get_target_constraints()).Each entry carries the translated
label, theoperatorsthe type permits (each with its own label), and the currently validchoices(Nonewhen the values cannot be enumerated).choicesis resolved on every call rather than cached: the realm list changes as realms are created and deleted, and a stale selection list would invite an admin to write a condition that can never match.
- privacyidea.lib.conditional_access.conditions.policy_conditions_are_scopable(policy: ConditionalAccessPolicy) bool[source]¶
Whether every condition of policy can be expressed as a predicate on the authentication log, so the policy’s count can be narrowed to the rows its conditions describe instead of the policy merely being gated on the current request (see
condition_sql_filters()).All or nothing, deliberately: a policy mixing a scopable condition with one that is not cannot have “half” of its conditions honoured by the query, and silently applying only the scopable half would count rows the admin excluded. Such a policy therefore stays on the gate-only path, which is the behaviour it had before scoping existed.
A policy with no conditions is not scopable - there is nothing to scope, and the caller must not take the scoped path for it.
- Parameters:
policy – the policy whose conditions are inspected
- Returns:
True only if the policy has at least one condition and every one of them names a known type with a
log_columnand a known operator, i.e.condition_sql_filters()can express all of them. False means the count must be left unscoped.
- privacyidea.lib.conditional_access.conditions.policy_matches_context(policy: ConditionalAccessPolicy, context: CAContext) bool[source]¶
Whether policy applies to the request described by context at all.
Every condition must hold (AND); a policy with no conditions applies to everyone. The engine calls this before counting anything, so a policy that does not apply costs no database work.
- Parameters:
policy – the policy whose conditions are checked
context – what is known about the request under evaluation
- Returns:
True if the policy applies to this request
17.2.1.5.8. Shipped policy templates¶
Ready-made conditional-access policy templates.
The templates are a catalog of default conditional-access policies.
Each is a ConditionalAccessPolicyTemplate constant referencing the AuthEventType
/ ConditionalAccessAction members directly (so a renamed event type or action
fails at import, not silently at runtime); policy is a full payload for
create_conditional_access_policy().
The shipped set is the single _TEMPLATES tuple - to add a template,
define a constant and add it there.
The REST API returns the whole catalog in one call
(list_conditional_access_policy_templates()); a client prefills a policy from a
template and submits it as a normal create request.
- class privacyidea.lib.conditional_access.policy_template.ConditionalAccessPolicyTemplate(key: str, description: object, policy: dict)[source]¶
One shipped conditional-access policy template.
- Variables:
key – stable catalog identifier
description – a
lazy_gettextstring, translated when serializedpolicy – the create-policy payload (see
policy)
- description: object¶
- key: str¶
- policy: dict¶
17.2.1.5.9. Live lock and block state¶
Management layer for the live conditional-access state: user locks
(UserLockState) and the blocklist
(BlockList).
The engine (privacyidea.lib.conditional_access.engine) writes this state
when a policy stage fires and reads it on the authentication pre-check. This
module is the management path — listing the current state, imposing a
restriction by administrator decision and clearing single entries — shared by the
REST API (/conditionalaccess) and the pi-manage conditionalaccess CLI, so
both go through one implementation.
- privacyidea.lib.conditional_access.state.LOCK_CAUSES = ('POLICY', 'MANUAL')¶
Who imposed the restriction now in force, as accepted by the
causesquery parameter.
- privacyidea.lib.conditional_access.state.LOCK_STATES = ('permanent', 'temporary', 'expired')¶
The states a user-lock record can be in, as accepted by the
statesquery parameter.
- privacyidea.lib.conditional_access.state.SORTABLE_COLUMNS = {'lock_cause': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'lock_expires_at': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'locked_at': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'realm': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'resolver': <sqlalchemy.orm.attributes.InstrumentedAttribute object>, 'username': <sqlalchemy.orm.attributes.InstrumentedAttribute object>}¶
The columns a paginated locked-users query may sort by, keyed by the name the API accepts.
- privacyidea.lib.conditional_access.state.block_ip(ip: str, duration_seconds: int | None = None, now: datetime | None = None) dict[source]¶
Block ip by administrator decision, replacing whatever block is currently on record, and return the new block in the shape of
_blocklist_dict(). The user-lock counterpart islock_user(), and the same authoritative-write reasoning applies.A never-block address (loopback, or one covered by
PI_CONDITIONAL_ACCESS_NEVER_BLOCK) is refused loudly. The engine skips such an address silently, which is right for an automatic action - it must not break an authentication over an allowlisted proxy - but wrong here: an administrator who asks for a block and gets a silent no-op has no way to tell it apart from success.- Parameters:
ip – the source IP to block
duration_seconds – how long the block lasts, or
Nonefor a permanent blocknow – the reference time; defaults to
utc_now()
- Raises:
ParameterError – if the IP is unparsable or on the never-block list, or the duration is not a positive integer
- privacyidea.lib.conditional_access.state.get_user_lock_dict(user: User, now: datetime | None = None) dict | None[source]¶
Return user’s current lock in the same shape as
list_locked_users(), orNoneif the user is not currently locked. The active/expiry decision is delegated toget_user_lock()so this always agrees with the authentication pre-check.
- privacyidea.lib.conditional_access.state.list_blocklist(include_expired: bool = True, now: datetime | None = None) list[dict][source]¶
Return the blocklist entries, most recently updated first. Each row carries the expiry fields (
permanent/block_expires_at/seconds_remaining), so the caller can tell a currently-enforced block from a stale, expired record. The never-block allowlist is an enforcement-time concern and is not applied here, so an admin can see a row even for a never-enforced IP - until the next authentication from that IP, which drops it (seeget_ip_block()).- Parameters:
include_expired – also return stale rows whose timed block has expired. Defaults to
True: a management view lists what is on record and the caller tells the two apart from the expiry fields. PassFalseto get only the blocks still in force.now – reference time; defaults to
utc_now()
- privacyidea.lib.conditional_access.state.list_locked_users(realms: list[str] | None = None, resolvers: list[str] | None = None, usernames: list[str] | None = None, states: list[str] | None = None, visibility_scopes: list | None = None, case_insensitive: bool = False, now: datetime | None = None, causes: list[str] | None = None, error_messages: list[str] | None = None) list[dict][source]¶
Return all matching locked users (no pagination), most recently updated first. See
_lock_conditions()for the filter/scoping semantics andlist_locked_users_paginate()for the paginated variant.
- privacyidea.lib.conditional_access.state.list_locked_users_paginate(realms: list[str] | None = None, resolvers: list[str] | None = None, usernames: list[str] | None = None, states: list[str] | None = None, visibility_scopes: list | None = None, case_insensitive: bool = False, page: int = 1, page_size: int = 15, sort_column: str = 'locked_at', sort_order: str = 'desc', now: datetime | None = None, causes: list[str] | None = None, error_messages: list[str] | None = None) dict[source]¶
Return one page of matching locked users plus pagination metadata
{locked_users, count, current, prev, next}— the counterpart oflist_locked_users()for the WebUI table. Filter/scoping semantics are as_lock_conditions(); sorting is by one ofSORTABLE_COLUMNS(fallbacklocked_at), always tie-broken by the primary key for a stable order across pages.
- privacyidea.lib.conditional_access.state.lock_internal_admin(login: str, duration_seconds: int | None = None, now: datetime | None = None) dict[source]¶
Lock the local database admin login by administrator decision, and return the new lock in the shape of
_locked_user_dict(). The local-admin counterpart oflock_user(), with the same authoritative, non-defensive write and the same permanent default; see there.A local admin has no
(resolver, uid, realm)to key a row on - only a login name - so the row is keyed asLockSubjectkeys it, and under the spelling theadmintable holds rather than the one that was typed: the authentication path counts and locks that name, so a lock written under any other would never be met (seecanonical_db_admin_login()).Only an existing account can be locked. Locking a name that is not one would leave a row nothing ever reads, which for a management call is a silent no-op rather than the refusal it should be - and unlike a userstore user, whose realm may simply have gone away, there is exactly one place a local admin can be looked up.
- Parameters:
login – the login name of the local database admin to lock
duration_seconds – how long the lock lasts, or
Nonefor a permanent locknow – the reference time; defaults to
utc_now()
- Raises:
ParameterError – if no such local admin exists, or the duration is not a positive integer
- privacyidea.lib.conditional_access.state.lock_user(user: User, duration_seconds: int | None = None, now: datetime | None = None) dict[source]¶
Lock user by administrator decision, replacing whatever lock is currently on record, and return the new lock in the shape of
_locked_user_dict().duration_secondsomitted writes a permanent lock (only an unlock clears it); a positive value writes a timed one. Permanent is the default because an administrator locking by hand is normally reacting to an incident: a lock that quietly expires on its own is the surprising outcome.Unlike the engine’s
_upsert_user_lock_statethis write is authoritative: it never declines as a weakening, so an admin may replace a permanent policy lock with a two-hour one. The engine’s never-weaken rule exists so that the order in which two automatic policies happen to fire cannot decide the outcome; an administrator setting a lock by hand is the decision. It is also not defensive - a management caller is waiting for the result, so a failed write raises instead of being indistinguishable from success.The row is stamped
RestrictionCause.MANUAL. Nothing else is needed to enforce it: the authentication pre-check reads the state row whoever wrote it.- Parameters:
user – the user to lock; must resolve to a
(resolver, uid, realm)identity, which is the row’s keyduration_seconds – how long the lock lasts, or
Nonefor a permanent locknow – the reference time; defaults to
utc_now()
- Raises:
ParameterError – if the user does not resolve, or the duration is not a positive integer
- privacyidea.lib.conditional_access.state.purge_expired_blocklist(now: datetime | None = None) int[source]¶
Delete blocklist rows that are no longer in force — a timed block past its expiry. Permanent blocks and active timed blocks are kept. Returns the number of rows removed.
- privacyidea.lib.conditional_access.state.purge_expired_user_locks(now: datetime | None = None, visibility_scopes: list | None = None) int[source]¶
Delete user-lock rows that are no longer in force — a timed lock past its expiry. Permanent locks (
lock_expires_at IS NULL) and active timed locks are kept. Nothing writes these rows off on its own, so this is the housekeeping that clears stale records. Returns the number of rows removed.visibility_scopesrestricts the purge to the caller’s authorization boundary (see_visibility_condition());Nonemeans unrestricted. A scoped admin only clears the stale rows they can see, so the returned count is the number they were allowed to remove.
- privacyidea.lib.conditional_access.state.remove_blocklist_entry(entry: str) bool[source]¶
Remove a single blocklist entry by its identifier (a source IP today). Returns
Trueif a row was removed,Falseif there was no entry.Both the canonical spelling of entry and entry as it was typed are removed: canonicalizing alone would leave a row some other path filed under a different spelling undeletable, and it is the same address either way (see
canonical_block_identifier()).
- privacyidea.lib.conditional_access.state.unlock_internal_admin(login: str, visibility_scopes: list | None = None) bool[source]¶
Delete the lock of the local database admin named login, whichever spelling of that name it stands under. Returns
Trueif a row was removed,Falseif there was no lock. The by-name counterpart ofunlock_internal_admin_by_uid(), which removes one row by its own key; this is for a caller holding a typed name rather than a listed row, such aspi-manage conditionalaccess unlock-user --admin.Both the canonical spelling and the one given are matched, and for the same reason the lock is written under the canonical one: where the
admintable folds case, every spelling authenticates the same account, so every row standing under one of them bars that account from logging in and all of them have to go. Matching only the canonical spelling would strand a row whose account was since removed and recreated under a different one - and a lock outliving its admin is exactly the row an operator needs to be able to clear.visibility_scopesrestricts the delete to the caller’s authorization boundary as elsewhere. A local admin’s row carries no realm or resolver, so a realm- or resolver-scoped administrator matches none of it and cannot lift such a lock - which is the intended answer: the account is outside their boundary.
- privacyidea.lib.conditional_access.state.unlock_internal_admin_by_uid(uid: str, visibility_scopes: list | None = None) bool[source]¶
Delete the one local-admin lock row keyed on uid. Returns
Trueif it was removed,Falseif there was no such row.The exact-key counterpart of
unlock_internal_admin(), for a caller that already holds the row - the locked-users table, which lists it and then acts on what it listed. Nothing is derived and nothing else is touched: the name is not looked up in theadmintable, so a row cannot be missed because the account it belongs to is gone or now spelled differently, and a second row under a second spelling is left alone rather than removed along with the one that was asked for.
- privacyidea.lib.conditional_access.state.unlock_user_by_id(uid: str, realm: str, resolver: str | None = None, visibility_scopes: list | None = None) bool[source]¶
Delete the lock(s) for a
(uid, realm[, resolver])identity. ReturnsTrueif any row was removed,Falseif there was no lock. Likeunlock_user_by_username(), this performs no live resolver lookup — it matches the stored row columns directly, so it works even for a user that no longer resolves or whose login has since changed.resolveris optional and only narrows the match when supplied — mirroringunlock_user_by_username()(resolver is always a disambiguator, never a required part of the key). Omitting the resolver clears the lock for every matching uid in the realm; pass a resolver to target exactly one.visibility_scopesis the caller’s authorization boundary (see_visibility_condition());Nonemeans unrestricted. It is part of theDELETEcriterion rather than a pre-flight check because one call may match several rows: a scoped admin must not clear a row outside their boundary via a call that also matches one inside it. An out-of-scope target is therefore indistinguishable from an absent lock — both returnFalse.
- privacyidea.lib.conditional_access.state.unlock_user_by_username(username: str, realm: str, resolver: str | None = None, visibility_scopes: list | None = None) bool[source]¶
Delete the lock(s) for a
(username, realm[, resolver])identity. ReturnsTrueif any row was removed,Falseif there was no lock.usernameis the denormalized login and is not unique, so more than one row may match (e.g. a stale row from a since-recreated login, or the same login across resolvers); all matches are removed.resolveris optional and only narrows the match when supplied.visibility_scopesrestricts the delete to the caller’s authorization boundary exactly as inunlock_user_by_id().
- privacyidea.lib.conditional_access.state.user_matches_scopes(user: User, scopes: list | None) bool[source]¶
Whether a fully-resolved user falls within any of the admin’s visibility scopes (
None= unrestricted).The predicate form of
_visibility_condition(), for the one caller that has a single identity in hand rather than a query to narrow. The two must answer alike, so a scope setting no dimension at all admits nothing here as well: falling through to “matches” would read a boundary that names nothing as a boundary that permits everything, which is not what the other form answers.get_policy_visibility_scopesdoes not currently build such a scope - it answersNonefor unrestricted instead - so this aligns the two rather than changing any of today’s answers.user_rolesis honoured for the same reason: a scope naming roles is enforced by the SQL side, and a user is only ever theuserrole, so a scope confined to local administrators does not contain one.
17.2.1.5.10. Per-request context¶
Per-request buffer of the conditional-access work this request will do.
One logical authentication produces its authentication-log row from any of a dozen call sites, and two post-policies
may afterwards correct that row. Rather than have each of them write (and re-write) independently, they stage a
PendingAuthEvent here and the rows are written
together - the same shape the audit log uses with g.audit_object.
The buffer lives on g, so it is per app context (and thus per request) exactly like the conditional-access
session it writes on.
- class privacyidea.lib.conditional_access.request_context.AuthPrincipal(user: ~privacyidea.lib.user.User = <factory>, username: str | None = None, internal_admin: bool = False)[source]¶
Who this request is authenticating, recorded once and used by both the log rows and the policy evaluation.
user alone is not enough to describe every principal, which is why the other two fields exist. A resolved user carries
(resolver, uid, realm, login); an unresolved one (an unknown login) still carries login and realm with resolver empty and uidNone, which is exactly what the log stores. A local database admin, however, has no user object at all - the login is not kept there - so it arrives as username, and internal_admin marks it so the row’suser_rolesaysadmin-internalrather thanuser.user defaults to an empty
Userrather thanNoneso the engine can always read.resolver/.uidoff it; an empty one is simply never “resolved” and so never locked.This tracks the most recently logged identity, and deliberately does not reach back into events already staged. Each event captures the identity it was logged for.
- internal_admin: bool = False¶
- username: str | None = None¶
- class privacyidea.lib.conditional_access.request_context.ConditionalAccessContext[source]¶
The conditional-access work of one request: who is authenticating, and the authentication-log rows it will write.
Rows are held as a list rather than a single row because one request can legitimately produce several: a
push_waitlogin logs the challenge trigger and then the terminal outcome within the same blocking request. They are written in staging order, so the log reconstructs the sequence.- add_outcomes(outcomes: list[ConditionalAccessOutcome]) None[source]¶
Buffer what conditional access decided before this request logged anything - the pre-auth DENY decision, enforced or dry-run.
There is no row to record them against yet, and for a rejected request there will not be one until the pre-check stages its own event. So they wait here and the next staged event takes them over (
stage()). A request that never stages an event drops them, which is correct: with no authentication event there is nothing the outcome could belong to, and the decision will be re-derived on the next request that does log one.
- property amendable: PendingAuthEvent | None¶
The staged event a later request stage may correct, or
Noneif there is none.That is
latest, with two exceptions - both events that record something other than the outcome the request’s token logic reached, and that a later stage must therefore not overwrite. A caller that finds nothing amendable stages its own event instead.An
immediateevent records something that happened at that point - thepush_waitchallenge trigger, which a concurrent/ttype/pushhas to be able to read. It matters where the terminal event is suppressed (apush_waittimeout): the trigger is then the only staged event, and reclassifying it would destroy the trigger record instead of logging the corrected outcome.A
CA_ENFORCEMENT_EVENT_TYPESevent records that conditional access turned the request away before any token logic ran - the one place an admin can see why it was refused. The post-policies still run on the gate’s rejection response (the gate is the innermost decorator), so without this they would relabel that row: the reason would be lost, and the relabelled event would pass the matching guard inrun_post_eval()and let the lock feed itself.
- property amended: list[PendingAuthEvent]¶
The staged events whose row exists but no longer matches the event, in staging order.
- property attempt_id: str¶
The id correlating everything this request contributes to one logical authentication attempt.
An attempt spans as many requests as the flow needs - a challenge trigger, a wrong answer, the retry that succeeds - and every authentication-log row of those requests carries this id, so a policy can count attempts rather than rows. It is minted on first use and then fixed for the rest of the request, so the challenge the request triggers and the rows it logs cannot disagree about which attempt they belong to.
A request continuing an earlier attempt takes that attempt’s id over first (
continue_attempt()); one that continues nothing starts a new attempt here.
- property attempt_resolved: bool¶
Whether this request has settled on an attempt yet, without settling on one by asking.
Reading
attempt_idmints an id as a side effect, so this is the only way to tell “we joined a known attempt” from “we are about to start a new one” - the difference between a correctly correlated row and a silently orphaned one.
- claim_message(message: str) None[source]¶
Claim message as conditional access’s own wording for this response, so
hide_specific_error_messageandno_detail_on_failshow it instead of their own generic text (seeclaimed_ca_message()).Only the gates claim, they being the only place a conditional-access message is ever said: their responses are built inside the decorator stack, where those two actions can still reach them.
- property classifying: PendingAuthEvent | None¶
The staged event that classifies what this request authenticated, or
Noneif nothing was staged.latest, except that aCLIENT_SIGNAL_EVENT_TYPESevent is passed over while any other staged event remains. Such an event describes the client a request arrived with, not an outcome the request reached, and it is staged on the way out - after the view has staged the real outcome - so aslatestit would stand in for that outcome and decide which policies are evaluated (run_post_eval()asks the engine about one event type). A caller able to produce one at will could then keep every policy tracking its actual failures from ever being asked about them, which is the same hazardNON_REPRESENTATIVE_EVENT_TYPESalready keeps off the counting side.A client signal is still returned when it is all there is - a request that authenticated nothing has no classification for it to stand in for, so a policy tracking it can fire there and nowhere is it hiding anything.
- confirm_attempt(transaction_id: str | None = None) None[source]¶
Settle on the attempt claimed by
continue_attempt(), because this request has been shown to be continuing that challenge rather than merely naming it.Called from the places that consume a challenge: the challenge-response branch of the token layer, which only reaches it for a token that actually holds a challenge for the presented transaction, the passkey branch of
/auth, and the out-of-band push answer. Answering wrongly still counts as continuing - a fumbled step of a chain belongs to the attempt it is a step of - so this deliberately does not wait for success.A no-op once the attempt is settled, and when there is nothing claimed. transaction_id, when given, has to be the transaction the claim was read from, so a request that consumes one challenge cannot settle on an attempt it borrowed from another.
- confirm_attempt_for_serials(serials: Iterable[str]) None[source]¶
Settle on the claimed attempt when its challenge belongs to one of serials - the tokens this request is authenticating against.
The link the claim was missing. A request that is answering a challenge is a request about the token that challenge was issued for, whatever becomes of the answer: the token may be disabled, out of its validity period or otherwise unusable, and the row still belongs to the attempt it is a step of. A request that merely carries someone’s transaction id is about no such token, and keeps an attempt of its own.
- continue_attempt(transaction_id: str | None) None[source]¶
Note the attempt the challenge transaction_id was triggered for, so this request’s rows can be grouped with it instead of starting an attempt of their own.
Claimed, not joined. Naming a transaction is not the same as continuing it: a request may carry a
transaction_idit never uses -/authreads it only on the passkey branch, and echoes it onto the row either way - so anyone holding any live transaction id could otherwise have an unlimited number of failures counted as one attempt, which is what a PER_ATTEMPT threshold counts. The claim is therefore held aside untilconfirm_attempt()is told the request actually engaged with that challenge, and dropped otherwise.The attempt id is stored in the challenge’s own data when the challenge is created (
create_challenge()), which is why this reads the challenge rather than the authentication log: the grouping travels with the very thing the client hands back, so no row has to be committed - nor the log indexed bytransaction_id- for an attempt to be recovered.Because a successfully answered challenge is deleted by the token logic, this has to run before that logic: the endpoints that answer a challenge do it in
before_request. A caller that only learns the transaction afterwards calls it itself - the out-of-band/ttype/pushanswer, which identifies its challenge by signature and leaves it in place, and any request whose own row is the first to name the transaction.A no-op once this request has settled on an attempt, so the earliest (and therefore most specific) caller wins. Also a no-op when the transaction has no challenge left - expired, cleaned up, or never existed - in which case
attempt_idmints a fresh id and the row is at worst grouped as its own attempt rather than left ungrouped.
- finalize() None[source]¶
Write everything staged and then evaluate the policies against it. Called from request teardown; both halves are guarded, so this never raises.
- flush() bool[source]¶
Bring the database in line with everything staged: insert the events that have no row yet, oldest first, re-write the rows of events amended since they were written, and record the conditional-access outcomes waiting on a row id.
Idempotent, so it is safe to call at any point and again at request teardown: an event that is already stored and unchanged is skipped, and outcomes already recorded are dropped from the event. Guarded internally - a failure is logged and swallowed, and the affected events keep their “needs writing” state so a later flush retries them.
- Returns:
whether everything staged is now stored as the events describe it
- property has_data: bool¶
Whether anything has been staged at all (written or not). Mirrors
audit_object.has_data.
- join_attempt(transaction_id: str | None) None[source]¶
Join the attempt of the challenge transaction_id outright, for a caller that resolved that challenge itself rather than being handed its id by the client.
continue_attempt()withholds the claim because a transaction id arriving in the request proves nothing: anyone can name a live transaction. That reasoning does not apply where the server found the challenge on its own - the out-of-band push answer matches one by verifying a signature over its nonce, the client having sent no transaction id at all - and there the engagement with the challenge is the thing that produced the id. Nothing further can confirm it, either: such a caller only learns the transaction while logging the row, at which point a claim left unsettled would already have been minted into an attempt of its own.A no-op once this request has settled on an attempt, so a challenge created and answered inside one request keeps the attempt it started with.
- property latest: PendingAuthEvent | None¶
The most recently staged event, or
Noneif nothing was staged.This is the event a later request stage amends: it classifies the request’s outcome, and where a request stages several (
push_wait: the challenge trigger, then the terminal outcome) the last one is the terminal one.
- reclassify(event_type: AuthEventType, reason_detail: dict | None = None, **fields: Any) None[source]¶
Correct the outcome of this request: assign event_type (and any other fields) to the staged event.
Nothing else has to be updated - the policy evaluation reads the classification straight off the event (see
run_post_eval()), so correcting the event is all there is to it. fields are applied only when given, so a post-policy that has no serial of its own does not clear the logged one.reason_detail is merged into the event’s existing detail rather than assigned, which is why it is a parameter of its own instead of one more field: the detail is a namespace several layers write into (the token layer records why each of the user’s tokens failed, a post-policy the rule that overrode them), and assigning it - as passing
other_infowould - drops what the layer below recorded. Thereasonslist, in contrast, is an ordinary field and is replaced like any other: a caller correcting the outcome is saying the reasons it passes are the ones that now hold.With nothing
amendablethis is a no-op: a caller with no event of its own must stage one instead.
- property rejected_by_conditional_access: bool¶
Whether conditional access itself turned this request away (see
CA_ENFORCEMENT_EVENT_TYPES).The gate is the innermost decorator, so the post-policies still run on its rejection response and would otherwise classify a request that never reached any token logic. There is nothing for them to say about it: the request was refused for a reason already recorded, and logging their own outcome on top would both bury that reason and hand the conditional-access counters an attempt the lock itself produced.
- run_post_eval() None[source]¶
Let the conditional-access engine react to what this request logged.
Nothing is reported back, because nothing is reported to the client: a restriction this request writes applies from the next request, which the pre-check refuses (see
conditional_access_precheck()). The response in flight keeps whatever it had coming.Nothing has to be scheduled: staging an authentication event is the signal, and everything the engine needs is already recorded - the classification comes from the request’s
classifyingevent, the principal and source IP from the request’sAuthPrincipalandsource_ip. That removes the second copy of those values that a separate “schedule” step would keep, and with it any chance of the two disagreeing after areclassify().Only the classifying event is evaluated, which is one evaluation per request. Where a request stages several (
push_wait: the challenge trigger, then the terminal outcome) the earlier ones are still counted - counts are taken over the stored rows - they just do not each provoke their own evaluation.Idempotent per classification, not merely once: once the engine has returned for one, a repeated call is skipped, while a post-policy that corrects the outcome in between is evaluated again - the engine would otherwise be left having judged a classification that no longer holds. Request teardown is the only caller, so nothing reaches that guard today; it is what keeps the evaluation safe to drive from anywhere else.
The evaluation counts events over the authentication log, so it must run after
flush()- otherwise the count would miss the very event that triggered it. That ordering also keeps the counts from reading a stale snapshot: under MySQL/MariaDB’s REPEATABLE READ an open read transaction hides rows a concurrent request committed since it began, and the flush commits, so the counts start from a fresh view on every backend. The pre-check leaves none open either, having released its connection (release_ca_connection()). Should a caller ever reach here without a preceding commit, that no longer holds and the read view has to be ended explicitly first.Every error is swallowed: this only writes state that the next request consults and must never affect the response that already completed.
What the engine decided comes back as outcomes, and they are recorded here against the row of the event it judged - a dry-run policy’s included, since that records what it would have done. The row id is available because
flush()ran first; had the row not been written, the outcomes are dropped with a log message rather than stored without the request they belong to.The
CAContexta policy’s conditions are matched against is assembled here rather than bybuild_ca_context(): everything it needs is already recorded, so this stays Flask-free and - more importantly - the conditions are evaluated against exactly the identity the row states.user_roleis taken off the event for that reason: it was determined when the event was staged, from theinternal_adminflag the caller verified, which a local database admin cannot be classified without.usernamecomes off it for the same reason, and is the other half of that identity: a local admin has no user object, so the pair is all a policy can count and lock them by (seelock_subject()).The event types conditional access writes for its own rejections are skipped: evaluating them would let a lock feed itself, since a locked user’s rejected requests would keep the count above the threshold forever. They are also absent from the trackable vocabulary, so no policy could match one anyway - this saves the query and keeps the guarantee readable where the evaluation happens (
CA_ENFORCEMENT_EVENT_TYPES).What is evaluated is the request’s
classifyingevent rather than simply the last one staged, because the engine is asked about a single event type and a client signal staged on the way out would otherwise be it - see there.
- stage(event: PendingAuthEvent) PendingAuthEvent[source]¶
Add event to this request’s buffer and return it, so the caller can keep the handle - a later stage can still amend the event, and its
row_idbecomes available once it is written.Any outcomes buffered by
add_outcomes()are handed to this event, so they are written as soon as its row id is known.
- property unwritten: list[PendingAuthEvent]¶
The staged events that have no row yet, in staging order.
- class privacyidea.lib.conditional_access.request_context.GateCheck(resolve_identity: Callable[[], User], check: Callable[[User], Any], identity: User)[source]¶
The conditional-access gate a request passed, kept so it can be run again when a pre-event handler changes who the request is for (see
recheck_conditional_access_gate()).- Variables:
resolve_identity – resolves the identity the gate checks from the request as it stands now
check – runs the gate for an identity, returning or raising what the gate does for a refused request
identity – the identity the gate last checked
- privacyidea.lib.conditional_access.request_context.claimed_ca_message() str | None[source]¶
The error message conditional access claims for this response (or
AuthError), orNonewhen it wrote none.hide_specific_error_messageandno_detail_on_failexist to suppress what privacyIDEA volunteers by default - which factor failed, why the token refused. A conditional-access message is the opposite: an admin either wrote it on the stage or turned it on by policy. The two are separate concerns, so both actions show this wording rather than their own generic text, and suppress everything else as usual - which costs a rejection nothing, since it has nothing else to say.Read with
peek_ca_context(), so asking the question on a request that never touched conditional access does not bring a buffer into existence.
- privacyidea.lib.conditional_access.request_context.confirm_attempt(transaction_id: str | None = None) None[source]¶
Settle on the attempt this request claimed, because it has been shown to be continuing that challenge (
ConditionalAccessContext.confirm_attempt()).Safe to call outside a request: there is then no attempt to speak of, and none is created here - a request that claimed nothing has nothing to settle, and giving it a buffer to establish that would be pointless.
- privacyidea.lib.conditional_access.request_context.confirm_attempt_for_serials(serials: Iterable[str]) None[source]¶
Settle on the claimed attempt when its challenge belongs to one of serials (
ConditionalAccessContext.confirm_attempt_for_serials()).
- privacyidea.lib.conditional_access.request_context.continue_attempt(transaction_id: str | None) None[source]¶
Let this request join the attempt the challenge transaction_id was triggered for (
ConditionalAccessContext.continue_attempt()).For
before_request, which has to do this ahead of the token logic. A request that carries no transaction continues nothing, and is not given a buffer just to establish that.
- privacyidea.lib.conditional_access.request_context.current_attempt_id() str | None[source]¶
The attempt id of the request in progress, or
Nonewhen there is no request to attribute anything to.For
create_challenge(), which stamps it into every challenge so a later request answering that challenge can rejoin the attempt.An attempt is a property of one HTTP request, so this deliberately tests for a request context rather than merely an app context. A
pi-managecommand or a periodic task runs inside an app context and would otherwise be handed an attempt id - and since the buffer lives ong, which such a task holds for its whole run, every challenge it created would be stamped with the same id and read back as one authentication attempt. Outside a request there is no attempt to speak of, so the challenge carries none and a request answering it starts its own.
- privacyidea.lib.conditional_access.request_context.get_ca_context() ConditionalAccessContext[source]¶
Return this app context’s
ConditionalAccessContext, creating it on first use.
- privacyidea.lib.conditional_access.request_context.join_attempt(transaction_id: str | None) None[source]¶
Join the attempt of a challenge this caller resolved itself (
ConditionalAccessContext.join_attempt()).
- privacyidea.lib.conditional_access.request_context.peek_ca_context() ConditionalAccessContext | None[source]¶
Return this app context’s buffer if one was created, else
None- without creating one.For request teardown, which has to flush whatever a request staged but should not bring a buffer into existence for the many requests that never log an authentication event.
- privacyidea.lib.conditional_access.request_context.recheck_conditional_access_gate() Any[source]¶
Run the conditional-access gate this request passed again if the identity it checks has changed since.
The gates sit above the pre-policies and the event handlers, so nothing runs for a locked user before the request is refused. A pre-event handler can change who the request is for after that: the RequestMangler replaces
request.Userwithreset_user, and can rewrite theserialorcredential_idan endpoint resolves the token owner from without touchingrequest.Userat all. The event decorator therefore calls this after every pre-event handler, and the identity is resolved again the way the gate resolved it, so a change to either is noticed before any later handler or the view acts for it. Every identity the request acts for is thereby one the gate has checked.The decision the first check buffered is dropped: it was about an identity this request no longer acts for, and the row it would be recorded on is the new one’s.
- Returns:
what the gate returns for a refused request - the rejection response on
/validate/*, while/authraises instead - orNonewhen the request may continue, passed no gate, or still acts for the identity the gate checked
- privacyidea.lib.conditional_access.request_context.reset_ca_context() None[source]¶
Discard this app context’s buffer, staged events and all, so the next
get_ca_context()starts empty.A real request gets a fresh
gand therefore a fresh buffer; this exists for the test suite, which pushes one app context per test class and would otherwise carry one test’s staged events into the next. Deliberately discards rather than flushes: leftovers from a test body are not rows anybody asked to persist.
17.2.1.5.11. Evaluation context¶
The request context the conditional-access engine evaluates against.
CAContext is the single parameter object carrying everything the engine
knows about the request under evaluation. It exists so that a new evaluation
input - an API-key status, a request header - is a new field
rather than a new parameter on every entry point and every internal helper along
the way. The engine’s two entry points
(evaluate_access_decision() and
evaluate_conditional_access_policies())
take it instead of the individual values.
It is deliberately free of Flask: the lib layer must stay usable outside a
request (an authentication event can be recorded from outside a view, e.g. the
push_wait flow). The API-layer factory
build_ca_context() reads g / request and
fills the fields in; outside a request context the request-scoped fields are
simply None.
Every field is optional. A field that could not be determined is None, and it
is the consumer’s job to decide what that means - a policy condition declares
whether missing data makes it match or not match, and the engine’s counting paths
already skip a subject they cannot identify (an unresolved user, an absent source
IP). Nothing here raises.
- class privacyidea.lib.conditional_access.context.CAContext(user: User | None = None, source_ip: str | None = None, endpoint: str | None = None, user_role: str | None = None, username: str | None = None, own_row_ids: tuple[int, ...] | None = None)[source]¶
What the conditional-access engine knows about the request being evaluated.
Frozen because the context describes one request and must read identically at every point of the evaluation: the pre-auth decision, the counting, and the post-response actions all have to agree on who and what they are judging.
- Variables:
user – the authenticating user.
user-target policies key their count and their lock on this user’s(resolver, uid, realm)tuple and therefore ignore an unresolved one;source_ip-target policies act regardless of it. A local database admin has none at all, and is described byusernameanduser_roleinstead.source_ip – the resolved client IP, as used by the audit log.
source_ip-target policies count and block on it.endpoint – the endpoint the request authenticates against, as its path (
/auth,/validate/check,/ttype/push). AnENDPOINTcondition compares against it, so a policy can restrict itself to - or exempt - one way in; it is the same value the authentication log’sendpointcolumn stores, which is what lets such a condition also scope the counting query. Seerequest_endpoint().user_role – the principal’s role (
AuthLogUserRole), as recorded in the authentication log. Pre-auth this is the claimed role - an admin realm, or a local admin name that exists - since no credential has been checked yet; that is what lets a break-glass condition exempt an emergency admin from a pre-auth DENY. Seebuild_ca_context()for where it comes from.username – the login name, as the authentication log records it. For a local database admin this is the whole identity - no user object, no resolver, no realm - so together with a
user_roleofadmin-internalit is what auser-target policy counts and locks them by (seelock_subject()). For everyone else it merely repeats the user’s login, and for an unknown login it is the name that was tried.own_row_ids – the ids of the authentication-log rows this request itself wrote, however many (a multichallenge or push_wait flow logs several within one request). Used only post-auth, to compute a count as it stood before this request’s own rows joined it (see
_count_events()and_count_attempts()) - the pre-auth decision has nothing of its own logged yet, so it never sets this. Deliberately not the request’sattempt_id: that id is shared by every request of a multi-request attempt (a challenge trigger, a wrong answer, the retry that succeeds - seeConditionalAccessContext.attempt_id), so excluding by it would also exclude an earlier request’s rows that an earlier evaluation already counted, not just this request’s own contribution.None/empty when unavailable (outside a request context, or nothing written yet), in which case that count simply is not computed.
Note what is deliberately absent: the authentication log’s
client_label(theclient_idparameter, falling back to the User-Agent header). It identifies the calling application well enough to be worth recording forensically, but a client picks it itself, so it must not gate a security decision - a policy scoped to it would be bypassed by editing a header. The calling application becomes a usable condition input once API keys give it an identity the server verifies.- endpoint: str | None = None¶
- own_row_ids: tuple[int, ...] | None = None¶
- source_ip: str | None = None¶
- user_role: str | None = None¶
- username: str | None = None¶
17.2.1.5.12. Database session¶
The database session the conditional-access subsystem writes on.
The authentication log and the lock/blocklist state are written while an authentication response is still in
flight, and they must never interfere with the request’s own work. On the shared db.session they do: committing
a log entry commits whatever else the request has pending at that moment, and rolling back a failed write discards
it. Both effects are invisible at the call site, which is why these writes get a session of their own.
The session is bound to the very same engine as db.session – same database, same connection pool. Only the
transaction is separate; nothing here implies (or supports) storing the conditional-access tables elsewhere.
Sharing the pool is what makes release_ca_connection() worth calling: a caller that is done reading hands
the connection back rather than holding it beside db.session’s own until teardown.
- class privacyidea.lib.conditional_access.session.WriteOutcome(succeeded: bool = False, error: Exception | None = None)[source]¶
Result of a
guarded_write()block: whether the writes were committed, and the exception that prevented it otherwise. A caller that only needs “best effort” can ignore it entirely.- error: Exception | None = None¶
- succeeded: bool = False¶
- privacyidea.lib.conditional_access.session.close_ca_session(*_args) None[source]¶
Close the conditional-access session of the current app context and drop it from the store, returning its connection to the pool.
Idempotent, and safe to call when no session was ever created: the next
get_ca_session()simply opens a fresh one. Registered both as a request finalizer and as an app-context teardown handler (seeinit_ca_session()), so it does run twice per request – hence taking, and ignoring, the teardown handler’s exception argument.
- privacyidea.lib.conditional_access.session.get_ca_session() Session[source]¶
Return the conditional-access session of the current app context, creating it on first use.
All conditional-access reads and writes share this one session, so a count query always sees the rows this request itself wrote: under MySQL/MariaDB’s REPEATABLE READ, a row committed by another session after the reading transaction began would be invisible to it.
A plain
Sessionis enough – the store it is cached in is already local to the app context (and thus to the thread), so wrapping it in ascoped_sessionas the SQL audit module does would add a thread-local registry that nothing here can reach.
- privacyidea.lib.conditional_access.session.guarded_write(description: str, session: Session | None = None, reraise: bool = False) Iterator[WriteOutcome][source]¶
Run a block of conditional-access writes as one transaction: commit it on success, roll it back on failure.
Failures are swallowed by default, because these writes happen while an authentication response is in flight and must never break it – a lost log entry or lock row is bad, a failed authentication is worse. The session is left usable either way, so the rest of the request (and the audit entry it still has to write) is unaffected.
Wrap one write per block, not a whole group of them: committing each separately means only one row lock is ever held at a time. A block that locked a
UserLockStaterow and aBlockListrow together (as one triggered stage can) would let two concurrent requests acquire them in opposite order and deadlock on InnoDB.Note the caller must not hold a flushed-but-uncommitted write on
db.sessionwhen this runs: on SQLite, which locks the whole database for writing, the commit then waits out the driver’s lock timeout and fails (seeGuardedWriteTestCase.test_write_lock_on_the_request_session_is_a_contained_failure). Reads ondb.sessionare harmless.- Parameters:
description – what is being written, as a noun phrase for the log message, e.g.
f"the user lock state for {user!r}"session – the session to write on; defaults to the conditional-access session
reraise – propagate the failure after rolling back. For management and CLI paths, where an admin is waiting for the outcome and a silent failure would be indistinguishable from “nothing matched”.
- privacyidea.lib.conditional_access.session.init_ca_session(app) None[source]¶
Register
close_ca_session()as an app-context teardown handler on app.call_finalizersonly runs fromteardown_request, so a session opened outside a request –pi-manage, a script, a periodic task – would hold its connection until the app context is garbage collected. Closing on app-context teardown covers those callers too.
- privacyidea.lib.conditional_access.session.release_ca_connection() None[source]¶
End the current transaction of the conditional-access session, returning its connection to the pool while keeping the session itself usable.
The authentication pre-check reads the lock, the block and the policies and then hands the request on. Its reads open a transaction that nothing commits, so without this the connection stays checked out until teardown – alongside
db.session’s own, out of the same pool – for the whole request, while the only conditional-access work left is the write at teardown. Releasing it here hands it back for the duration of the request the pre-check just let through, and the next use opens a fresh transaction.It also ends the read view: under MySQL/MariaDB’s REPEATABLE READ an open transaction hides rows a concurrent request committed since it began, which is exactly what the counts at teardown must not read (see
run_post_eval()).Safe for the pre-check because it carries nothing persistent forward: the restrictions come back as plain dataclasses and the outcomes it stages are transient (see
outcome_for_stage()). A caller holding an instance it still means to read must not use this.