Authentication and Authorization
Added in version 3.2.3.
Pelix provides an authentication and authorization layer: who is calling, which groups and roles they hold, and what they may do. It is transport-neutral, so the same credential store serves an HTTP request, a shell login or a message broker connection.
What this layer does not do
Pelix has no code-level permission model. There is no equivalent of OSGi’s
ConditionalPermissionAdmin, no sandbox and no signed-bundle verification. Any
bundle which gets installed can register a higher-ranked Authorizer and take
over every decision described below, or simply import pelix.security and call
run_as().
This layer therefore protects against remote callers, not against locally installed bundles. Read every guarantee below with that boundary in mind.
Four questions, four services
Question |
Service |
Shipped implementation |
|---|---|---|
How do I get credentials off this transport? |
(transport-specific) |
HTTP: Authentication |
Are these credentials valid, and who is it? |
|
|
Which groups and roles does this subject have? |
|
|
May this subject do this? |
policy file |
Plus exactly one facade, Authorization, which is what application code
injects or reaches through use_authorization().
Bundles
Bundle |
What it brings |
|---|---|
|
|
|
an |
|
roles from groups, permissions from roles, certificates to users, and the escape hatch |
pelix.security itself, holding the beans and the current subject, needs no
bundle at all: it imports the standard library and pelix.constants, and nothing
else.
The subject
A Subject is a complete, immutable snapshot of who is calling: a person, a
service account, a device, a peer framework, or the anonymous caller. It carries three
flat levels:
nameis the user;groupsis the membership an identity source asserted;rolesis the entitlement level a policy granted from those facts.
There is no membership graph, no nesting and no Role object. All three levels are
resolved once, when the subject is authenticated, so a queued execution path carries
its identity with it and needs no service call at the far end. The price is stated
next to the benefit: a membership change reaches a caller at their next
authentication, not immediately.
Identifiers are compared exactly
This layer folds nothing. No lower(), no casefold(), no Unicode
normalization, for user names, group names, role names or permission actions,
anywhere.
The first reason is conformance: the identifiers this layer handles are defined as
case-sensitive by the specifications which issue them, from the OpenID Connect sub
claim to OAuth 2.0 scope tokens. The second is that folding can only fail unsafely:
these are allow-lists, so a match which should not have happened grants access,
and every folding scheme widens the set of strings mapping onto a privileged name.
Folding belongs to whoever owns the matching rule. A provider sitting on a source which really is case-insensitive, such as an LDAP directory, applies that rule itself and documents the single canonical form it emits.
The cost is direct: a name has to be spelled identically in the identity source, in
the policy file and in the decorators. Dev from a directory against dev in a
policy file denies, silently, and presents as a policy bug rather than as the data bug
it is. When a check denies inexplicably, look at the spelling before looking at the
logic; the policy loader reports the two shapes such a typo usually takes.
The current subject
The caller is carried in a contextvars.ContextVar, and the rule is a
framework-wide one rather than a security feature:
The current subject follows the standard Python context. Wherever a Python context propagates, the subject propagates; wherever it does not, the subject does not, and the code crossing that boundary copies the context explicitly.
- pelix.security.get_current_subject() → Subject
Returns the subject of the current execution path.
The current subject follows the standard Python context: wherever a context propagates, the subject propagates, and code crossing a boundary a context does not cross copies the context explicitly.
- Returns:
The current subject, or ANONYMOUS when nothing was published
- pelix.security.run_as(subject: Subject) → Generator[None, None, None]
Runs the body of the
withblock as the given subject.This is privilege escalation by construction: in a framework with no sandbox, anyone who can import it can elevate. It is a readability tool, not a security boundary.
- Parameters:
subject – The subject to publish
Both are plain module functions, with no service and no bundle required. The asymmetry is deliberate: authorization needs policy, and therefore a service; identity is a fact, and it is free. It is also what makes the layer testable:
with run_as(Subject("alice", roles=frozenset({"admin"}), authenticated=True)):
obj.do_the_thing()
No framework, no bundle, no mock.
ThreadPool and the asynchronous HTTP service both carry the
context across their thread boundaries, so a subject published before a task is queued
is visible inside it.
Permissions
A Permission is an action, optionally scoped to a resource:
jobs.submit, jobs.submit:queue-a. Strings are parsed at the edges, once, so a
single type flows through the services.
The matching rule is small and complete. An action matches in one of three ways:
Grant action |
Matches |
|---|---|
|
exactly |
|
every action starting with |
|
every action. The only all-grant form |
And a resource in one of four:
Grant resource |
Request resource |
Result |
|---|---|---|
absent |
anything |
match: the grant is not resource-scoped |
|
anything |
match |
|
|
match |
|
absent, or any other |
no match |
A grant scoped to a resource therefore never satisfies a request naming none:
jobs.submit:queue-a does not imply jobs.submit. That is the safe direction.
Decorators
Read every one of them as “allow only”: @AllowGroup("dev") means “allow only
the dev group”. Each decorator narrows who can reach the target, and the names listed
inside one decorator are alternatives:
@AllowAuthenticated # allow only authenticated subjects
@AllowGroup("dev", "ops") # allow only these groups (any of them)
@AllowRole("admin") # allow only these roles (any of them)
@AllowPermission("jobs.submit") # parsed once, at decoration time
@AllowAll # no narrowing: overrides a class-level default
@DenyAll # total narrowing
@RunAs(Subject("batch", roles=frozenset({"operator"})))
The rule follows from that reading: any-of within one decorator, all-of when they
are stacked, and a method-level declaration replaces a class-level one entirely.
Stacking @AllowGroup("dev") and @AllowRole("admin") therefore means “only
members of dev who also hold admin”.
@AllowAuthenticated, @AllowAll and @DenyAll take no argument and are
written bare, without parentheses. The others always take at least one. No decorator
supports both forms, and applying an argument-taking one bare raises TypeError at
import time.
Applied to a class, a decorator sets the default of every function defined in that class body whose name does not start with an underscore. It does not reach inherited methods, and a method which carries its own declaration keeps it.
There is no @AllowUser. Deployment configuration may legitimately name a user;
source code should not.
What a refusal raises
The choice between the two exceptions is mechanical:
the current subject is not authenticated:
AuthenticationRequired. Over HTTP this becomes a 401 with a challenge, so a client can retry with credentials;the current subject is authenticated but does not satisfy the declaration:
AccessDenied, which becomes a 403. Retrying with the same credentials is pointless and the status says so.
@DenyAll always raises the second, even for an anonymous subject: no credential
would help, so offering a challenge would be a lie.
@RunAs is privilege escalation by construction: anyone who can import it can
elevate. In a framework with no sandbox it is a readability tool, not a security
boundary. There is no built-in all-powerful subject, which keeps it at worst a lateral
move: a system identity is an ordinary Subject("system", roles=frozenset({"system"}))
whose authority comes from the policy file.
Fail closed
Situation |
Behaviour |
|---|---|
|
every decorator but |
Started, no |
deny, with one warning |
Genuinely permissive wanted |
instantiate
|
You cannot become permissive by accident. State the consequence loudly in your own documentation: installing a library whose methods carry ``@AllowPermission``, and not starting the bundle, means those methods raise.
The pipeline
pelix.security.core.authenticate(credentials, source=None, *, method=None, transport=None) turns
credentials into a subject:
every
Authenticatoraccepting this kind of credentials is consulted inservice.rankingorder;every
MembershipProvidercontributes groups, and the results are unioned;the subject is rebuilt with those groups, and only then does every provider contribute roles;
the subject is returned, authenticated, with
methodandtransportset to the arguments the transport gave, or left unset for the transport to stamp later.
method names the mechanism (password, certificate, basic, …) and
transport the way the request came in (http, shell, …). They are kept
apart because several transports can use the same mechanism, and an audit has to tell
a login to an administration shell from a call to a service.
Step 3 is two passes rather than one, and that is load-bearing: it is what lets the policy file grant a role from a group a different provider asserted. With a single pass the policy would look at a subject whose groups are still empty and answer nothing.
The three-state authenticator contract
This is the most important detail of the pipeline. Two outcomes are not enough:
returning a
Subjectmeans success: stop;returning
Nonemeans abstain: not my credential kind, not my user, try the next one;raising
AuthenticationFailedmeans presented and wrong: stop, and do not consult lower-ranked authenticators.
Without the third state, a low-ranked fallback store silently becomes an oracle for
credentials a higher-ranked store already rejected: user admin exists in the main
store with one password and in an emergency .htpasswd with another, and the second
one keeps working forever.
An Authenticator must declare the credential kinds it accepts, in its
pelix.security.credentials service property. One which does not is never
consulted.
Brute-force throttling
authenticate(credentials, source=None) counts its failures, and refuses the
credentials of a key which failed too often without consulting any
authenticator. Two keys are tracked for each attempt:
the account: the credential kind and the user name for a password, the fingerprint for a certificate. Credentials naming no account have no account key;
the source, when the transport gives one in the
sourceargument, typically the client IP address.
After max_failures failures of a key within window seconds, that key is locked
out for lockout seconds. The count is a sliding window: once a lockout is over, one
more failure within the window locks the key out again, for twice as long, up to
max_lockout seconds. A key which stayed quiet for a whole window starts again from
scratch. A successful authentication clears the failures of its account, never those
of its source: a source which guessed one password right is not forgiven the failures
it made on other accounts.
A locked-out attempt raises the same AuthenticationFailed as a wrong
password, so that a caller cannot use the lockout to learn that an account exists. A
WARNING is logged once when a lockout starts, naming the key.
The throttle is configured with framework properties, read when the
pelix.security.core bundle starts:
Framework property |
Default |
Meaning |
|---|---|---|
|
5 |
failures which lock a key out.
|
|
900 |
seconds within which failures count |
|
60 |
seconds of the first lockout |
|
900 |
upper bound of a lockout, in seconds |
It lives in memory, in the framework process: a restart forgets it, and several frameworks behind a load balancer each count on their own. It tracks at most 10000 keys and forgets the least recently touched one beyond that, so that a flood of sources costs a bounded amount of memory; the price is that such a flood can make it forget a key early.
The trade-off. Anybody who knows a user name can lock that account out, by failing
on purpose, and the legitimate user is then refused from every source until the
lockout ends. Two things limit the damage. The failures which lock an account also
count against the attacker’s own source, so one source can only keep about one account
locked at a time, and gets locked out longer and longer while doing so. And a lockout
never exceeds max_lockout, so the denial of service ends on its own. A deployment
which cannot accept it for an account should authenticate that account with a client
certificate, which cannot be guessed, rather than with a password.
The locked-out answer is also immediate, while a wrong password costs a hash computation: timing tells a patient attacker that a key is locked, not whether its password was right.
Combining authorizers
One fixed, non-configurable rule: any DENY denies; otherwise any PERMIT permits;
otherwise deny. Decision.ABSTAIN is what lets independent policies compose.
An authorizer which raises denies: one which cannot decide has not decided.
The .htpasswd store
pelix.security.htpasswd provides both an Authenticator over a password
file and a MembershipProvider over a matching .htgroup.
Property |
Meaning |
|---|---|
|
path of the password file (mandatory) |
|
path of the group file |
|
accept an unrecognized hash as a plaintext
password. Default: |
Hash formats
Format |
Support |
|---|---|
|
supported, and recommended. |
|
supported. |
|
supported, with a warning: unsalted and unstretched |
|
bcrypt, when the optional |
DES crypt (13 characters) |
refused: eight-character truncation, twelve-bit salt |
anything else |
treated as a plaintext password, refused unless allowed |
The rounds= parameter of a SHA-crypt hash is capped at 100000. The format allows
999999999, which one login would turn into minutes of CPU.
The whole file is parsed when it is loaded, not entry by entry at login. An entry this build cannot verify is reported with its file and line number, and its user is left absent rather than present and unverifiable: a load-time failure is found by the operator at deploy time. A world-readable password file is reported too.
An unknown user is checked against a dummy hash before the store abstains, so that it does not answer visibly faster than a known one. One residual leak cannot be closed there and is worth knowing: with several stores registered, an unknown user is consulted against every one of them while a known user stops at the first.
The policy file
pelix.security.policy reads a TOML file granting roles from users and groups, and
permissions to roles:
[roles.admin]
users = ["thomas"]
groups = ["dev-leads"]
[roles.operator]
groups = ["dev", "ops"]
[permissions]
admin = ["jobs.*", "config.*"]
operator = ["jobs.read", "jobs.submit"]
Its path is the pelix.security.policy.file property.
The format is TOML because TOML keys are case-sensitive by specification, and role names are keys here: an INI file would have folded them in the very component which must fold nothing. Typed tables also say whether a name is a user or a group in the schema, and a duplicate key is a parse error rather than a silently kept last one.
Two things are reported when the file is loaded, and both are worth acting on:
every grant containing a
*, naming the file and the role. A wildcard is one typo away from full access;every dangling reference: a role granted to somebody but never given a permission, and a permission granted to a role nobody holds. Most spelling mistakes produce one of those two shapes.
This authorizer never returns DENY, only PERMIT or ABSTAIN: the format
expresses grants only, so a policy file can never veto a permission another, looser
authorizer allows. There is no implicit all-grant either: an empty [permissions]
table denies everything.
Client certificates
A transport which authenticated its peer with a TLS client certificate, such as the
remote shell (see Pelix Shell), turns it into ClientCertificate
credentials, of kind certificate:
fingerprint: the SHA-256 of the DER certificate, in lowercase hexadecimal with no separator;subject: the subject, as an RFC 4514 style string, most specific name first:CN=batch,O=Acme,C=FR;alt_names: the subject alternative names, astype:valuestrings:DNS:batch.example.com.
These credentials must only be built from a certificate the TLS layer already verified, from a context requiring a client certificate signed by a trusted authority. Nothing in this layer checks a signature, a validity period or a revocation: the object says “the peer proved it holds this certificate”, and an authenticator only maps it to a user.
The policy file maps certificates to users in its [certificates] tables, which
makes its component an Authenticator of certificate credentials:
[certificates.fingerprints]
"3F:5A:...:E9" = "thomas"
[certificates.subjects]
"CN=batch,O=Acme,C=FR" = "batch"
The groups and roles of the mapped user then come from the usual membership providers,
exactly as after a password login: a .htgroup file, the [roles] of the policy.
The two tables do not give the same guarantee:
a fingerprint names this very certificate, whoever issued it. It is written as
openssl x509 -noout -fingerprint -sha256 -in client.crtprints it, or in lowercase, with or without the:separators. Anything which is not a SHA-256 fingerprint, such as the SHA-1 one many tools print by default, refuses the file;a subject names whatever any trusted authority chose to issue under that name. It is only as strong as the least careful authority the transport trusts, so map subjects only behind a dedicated authority. It is compared exactly, like every other name of this layer:
CN=batch, O=Acmewith spaces is another string.
When a certificate matches both tables, the fingerprint wins. An unmapped certificate
abstains rather than fails: it passed the TLS verification, so it is not “presented and
wrong”, and another Authenticator may know it. The [certificates] tables
are validated as strictly as the rest of the file: an unknown key, a user name which is
not a non-empty string, or the same fingerprint written twice refuses the file.
Audit events
When an EventAdmin service is registered (see EventAdmin service), the
pelix.security.core bundle posts an event for every authentication and every
refusal:
Topic |
Posted when |
|---|---|
|
|
|
|
|
|
The properties of the two authentication events:
Property |
Value |
|---|---|
|
the name of the authenticated subject on success; on failure, the
user name a password tried, |
|
the credential kind: |
|
the |
|
the |
|
the |
|
failures only: |
And those of an access denied event: user and authenticated, from the refused
subject, plus permission (the refused permission, as a string) and declaration
(the decorator which refused it, such as AllowGroup('dev',)) when they apply.
No event ever holds a secret: neither a password nor any other part of the credentials but the user name. The failure reason is deliberately generic, like the exception a caller gets. Keep in mind that a user name field sometimes receives a password typed one line too early.
Authorization.is_permitted() posts nothing: a question is not a refusal, and a
page asking about ten menu entries must not report ten denials. Neither does
@AllowPermission with the pelix.security.core bundle stopped, since there is
then nothing to post through.
The events are posted asynchronously, and the EventAdmin service is looked up at each event: it may come and go. An event which cannot be posted is logged and dropped. The audit trail is never a condition of the decision: a missing or broken EventAdmin changes neither an authentication nor an authorization.
Reloading
Both bundles register as File Install listeners (see File Install), so writing the file is enough. Without that bundle the files are read once at validation, which is graceful degradation rather than a failure.
Two caveats come with it. File Install watches a whole folder, so the password file belongs in its own directory. And on a parse failure, a shape failure, an empty file or an unreadable one, the previous table is kept and an error is logged: an empty file is far more likely a partial write than an intentional revocation of everyone. A successfully parsed file with a user removed does revoke that user.
Worked example
/etc/pelix/auth/.htpasswd, in its own directory:
thomas:$6$rounds=10000$FGkY6bLp$1qE...
/etc/pelix/auth/.htgroup:
# groupname: user1 user2
dev-leads: thomas
/etc/pelix/auth/policy.toml:
[roles.admin]
groups = ["dev-leads"]
[permissions]
admin = ["jobs.*"]
The .ipopo initialization file (see Initial Configuration File):
{
"bundles": [
"pelix.ipopo.core",
"pelix.services.fileinstall",
"pelix.security.core",
"pelix.security.htpasswd",
"pelix.security.policy"
],
"components": [
{"factory": "pelix.security.htpasswd.factory", "name": "users",
"properties": {"pelix.security.htpasswd.file": "/etc/pelix/auth/.htpasswd",
"pelix.security.htpasswd.groups": "/etc/pelix/auth/.htgroup"}},
{"factory": "pelix.security.policy.file.factory", "name": "policy",
"properties": {"pelix.security.policy.file": "/etc/pelix/auth/policy.toml"}}
]
}
And, in a component:
import pelix.security.core
from pelix.security import UsernamePassword, run_as
from pelix.security.decorators import AllowPermission
@AllowPermission("jobs.submit")
def submit_job(name):
...
subject = pelix.security.core.authenticate(UsernamePassword("thomas", "..."))
# Subject(name='thomas', groups=['dev-leads'], roles=['admin'], ...)
with run_as(subject):
submit_job("nightly")
API
Beans
- class pelix.security.Subject(name: str, groups: frozenset[str] = frozenset({}), roles: frozenset[str] = frozenset({}), attributes: Mapping[str, ~typing.Any]=<factory>, authenticated: bool = False, method: str | None = None, transport: str | None = None)
A complete and immutable snapshot of who is calling: a person, a service account, a device, a peer framework or the anonymous caller.
The three levels are flat and immutable:
nameis the user,groupsis the membership asserted by an identity source, androlesis the entitlement level granted from those facts. There is no membership graph and no nesting.Every identifier is compared exactly, with no case folding and no Unicode normalization: a source whose matching rule is case-insensitive applies that rule itself and emits a single documented canonical form.
- method: str | None = None
Name of the mechanism which authenticated this subject: “basic”, “oidc”, …
- transport: str | None = None
Name of the transport this subject authenticated through: “http”, “shell”, …
Kept apart from
method: two transports can use the same mechanism, and an audit must tell an administration shell login from a service call.
- class pelix.security.Credentials
Base class of what a transport extracted, before it is validated.
KINDis what anAuthenticatoris selected on: it registers with the kinds it accepts in itsPROP_CREDENTIAL_KINDSproperty, and the core builds an LDAP filter from the kind of the object it was handed.
- class pelix.security.UsernamePassword(username: str, password: str)
A user name and a password, as HTTP Basic or a shell login produces them
- class pelix.security.ClientCertificate(fingerprint: str, subject: str = '', alt_names: tuple[str, ...] = ())
A client certificate, as a TLS transport received it.
Only build one from a certificate the TLS layer already verified (a server context with
verify_mode = ssl.CERT_REQUIREDand a trusted authority chain). Nothing here checks a signature, a validity period or a revocation: presenting this object means “the TLS handshake proved the peer holds the private key of this certificate, issued by an authority I trust”. An authenticator only maps it to a user.fingerprintidentifies this very certificate, whoever issued it.subjectandalt_namesare only as trustworthy as every authority the transport trusts, since any of them can issue another certificate with the same names.- classmethod from_der(der: bytes, details: Mapping[str, Any] | None = None) → ClientCertificate
Builds the credentials of a verified certificate.
The standard library cannot decode a DER certificate, so the subject and the alternative names come from the dictionary form of
SSLSocket.getpeercert(), which the ssl module only fills for a verified certificate. Without it, only the fingerprint is known.- Parameters:
der – The certificate, in DER form:
getpeercert(binary_form=True)details – The certificate as
getpeercert()decoded it, if available
- Returns:
The credentials
- classmethod from_socket(sock: ssl.SSLSocket) → ClientCertificate | None
Builds the credentials of the certificate the peer of a TLS socket presented.
The socket must come from a context which verified that certificate: see the class documentation.
- Parameters:
sock – A TLS socket, after its handshake
- Returns:
The credentials, or None if the peer presented no certificate
- alt_names: tuple[str, ...] = ()
The subject alternative names, as
type:valuestrings:DNS:host.example.com
- fingerprint: str
SHA-256 of the DER certificate, in lowercase hexadecimal, with no separator
- subject: str = ''
The subject, as an RFC 4514 style string:
CN=batch,O=Acme,C=FR
- class pelix.security.Permission(action: str, resource: str | None = None)
One action, optionally scoped to a resource:
jobs.submit,jobs.submit:queue-a.Strings are parsed at the edges, once, so that a single type flows through the service specifications.
- classmethod parse(spec: str) → Permission
Parses a permission specification.
- Parameters:
spec – An action, optionally followed by
:and a resource- Returns:
The parsed permission
- Raises:
ValueError – The action half is empty
- implies(other: Permission) → bool
Tells if this permission, read as a grant, satisfies the given request.
This is a pure string-matching helper on the bean, deliberately not the authorization decision: that one is
Authorization.is_permitted().- Parameters:
other – The requested permission
- Returns:
True if the grant covers the request
- class pelix.security.Decision(*values)
What an
Authorizeranswers.ABSTAIN is what lets independent policies compose: the combining rule is fixed, any DENY denies, otherwise any PERMIT permits, otherwise the request is denied.
Services
- class pelix.security.Authenticator(*args, **kwargs)
Specification of a credential store.
Authenticators are consulted in
service.rankingorder and the contract has three states, not two: without the third one, a lower-ranked store becomes an oracle for credentials a higher-ranked store already rejected.- authenticate(credentials: Credentials) → Subject | None
Validates the given credentials.
- Parameters:
credentials – What a transport extracted
- Returns:
A Subject on success, None to abstain (not my kind, not my user)
- Raises:
AuthenticationFailed – The credentials were presented and are wrong. No lower-ranked store is consulted
- class pelix.security.MembershipProvider(*args, **kwargs)
Specification of a provider of the groups and roles of a subject.
Every registered provider is consulted in both passes and the results are unioned. A provider may answer only one of the two, returning an empty iterable for the other.
- get_groups(subject: Subject) → Iterable[str]
Returns the groups of the given subject.
This runs on every provider before
get_roles()runs on any, sosubject.rolesis empty here by construction and must not be looked at.- Parameters:
subject – The subject being authenticated
- Returns:
The group names this provider asserts, verbatim
- get_roles(subject: Subject) → Iterable[str]
Returns the roles of the given subject.
The subject received here has its
groupsalready complete, which is what lets a policy grant a role from a group another provider contributed.- Parameters:
subject – The subject being authenticated, with its groups resolved
- Returns:
The role names this provider grants, verbatim
- class pelix.security.Authorizer(*args, **kwargs)
Specification of a policy.
The combining rule over the registered authorizers is fixed and not configurable.
- is_permitted(subject: Subject, permission: Permission) → Decision
Decides whether the given subject holds the given permission.
- Parameters:
subject – The subject to check
permission – The requested permission
- Returns:
PERMIT, DENY, or ABSTAIN to let another policy decide
- class pelix.security.Authorization(*args, **kwargs)
The authorization facade: the one service application code injects, or reaches through
use_authorization().subject=Noneeverywhere means the current subject.- check_permitted(permission: Permission, subject: Subject | None = None) → None
Checks that a subject holds a permission.
- Parameters:
permission – The requested permission
subject – The subject to check, or None for the current one
- Raises:
AccessDenied – The permission is not granted
- has_role(role: str, subject: Subject | None = None) → bool
Tells whether a subject holds a role. The name is compared exactly.
- Parameters:
role – The role to look for
subject – The subject to check, or None for the current one
- Returns:
True if the subject holds the role
- in_group(group: str, subject: Subject | None = None) → bool
Tells whether a subject belongs to a group. The name is compared exactly.
- Parameters:
group – The group to look for
subject – The subject to check, or None for the current one
- Returns:
True if the subject belongs to the group
- is_permitted(permission: Permission, subject: Subject | None = None) → bool
Tells whether a subject holds a permission.
- Parameters:
permission – The requested permission
subject – The subject to check, or None for the current one
- Returns:
True if the permission is granted
- pelix.security.use_authorization(bundle_context: BundleContext) → Generator[Authorization, None, None]
Utility context to use the authorization service safely in a “with” block. It looks after the authorization service and releases its reference when exiting the context.
- Parameters:
bundle_context – The calling bundle context
- Returns:
The authorization service
- Raises:
BundleException – Service not found
Exceptions
- class pelix.security.SecurityError
Root of the security exception family
- class pelix.security.AuthenticationFailed
Credentials were presented and are wrong
- class pelix.security.AuthenticationRequired
The caller is anonymous and needs a challenge: an HTTP transport answers 401
- class pelix.security.AccessDenied
The caller is authenticated but not permitted: an HTTP transport answers 403
The pipeline
- pelix.security.core.authenticate(credentials: Credentials, source: str | None = None, *, method: str | None = None, transport: str | None = None) → Subject
Turns credentials into a subject, with its groups and roles resolved.
The pipeline, which is the same whatever the transport was:
every
Authenticatoraccepting this kind of credentials is consulted in ranking order, under the three-state contract: a subject stops the loop, None abstains, andAuthenticationFailedstops it without letting a lower-ranked store answer;every
MembershipProvidercontributes groups, and the results are unioned;the subject is rebuilt with those groups, and only then does every provider contribute roles. The two passes are what lets a policy grant a role from a group a different provider asserted: with a single pass that rule would silently never fire;
the final subject is returned, authenticated, with
methodandtransportset to the given ones, unset by default.
methodnames the mechanism andtransportthe way the request came in, which is exactly what a transport-neutral pipeline cannot know: the caller gives them, or stamps them later withdataclasses.replace. Giving them here also puts them in the audit events.Failures are throttled per account and, when
sourceis given, per source. A locked-out key is refused before any authenticator is consulted, with the same exception as a wrong password: telling the caller that an account is locked would tell it that the account exists.- Parameters:
credentials – What a transport extracted
source – Where the credentials came from, such as the client IP address, if the transport knows
method – Name of the authentication mechanism: “password”, “certificate”, “basic”, …
transport – Name of the transport: “http”, “shell”, …
- Returns:
The authenticated subject
- Raises:
AuthenticationFailed – The credentials are wrong, no authenticator accepted them, or they are locked out
- pelix.security.core.post_event(topic: str, properties: dict[str, Any]) → None
Posts an audit event through the EventAdmin service, if one is registered.
The service is looked up at call time, since EventAdmin is optional and may come and go. The event is posted asynchronously and any error is logged and swallowed: an audit trail which could make authentication or authorization fail would turn a missing bundle into a denial of service, or worse, into a grant.
- Parameters:
topic – The event topic
properties – The event properties, which must never hold a secret
- class pelix.security.core.Throttle(max_failures: int = 5, window: float = 900.0, lockout: float = 60.0, max_lockout: float = 900.0, max_keys: int = 10000, clock: Callable[[], float]=<built-in function monotonic>)
Tracks authentication failures per key and locks out the keys which fail too often.
A key is an account or a source. After
max_failuresfailures withinwindowseconds, the key is locked out forlockoutseconds, doubling on each new lockout up tomax_lockout. The count is a sliding window: once a lockout ends, one more failure within the window locks the key again, for twice as long.Everything is in memory, and bounded: past
max_keystracked keys, the least recently touched one is forgotten, so that a flood of sources costs a fixed amount of memory. The price is that such a flood can also make the throttle forget a key early.- Parameters:
max_failures – Failures within the window which lock a key out
window – Length of the sliding window, in seconds
lockout – Length of the first lockout, in seconds
max_lockout – Upper bound of a lockout, in seconds
max_keys – Number of keys tracked at most
clock – A monotonic clock, in seconds: the wall clock can jump
- Raises:
ValueError – max_failures or max_keys is not strictly positive
- is_locked(keys: Iterable[str]) → bool
Tells whether any of the given keys is locked out.
- Parameters:
keys – The keys of an authentication attempt
- Returns:
True if at least one of them is locked out
- record_failure(keys: Iterable[str]) → None
Counts a failure against each of the given keys, locking out those which failed too often.
- Parameters:
keys – The keys of the failed attempt
- record_success(key: str) → None
Forgets the failures of a key, after a successful authentication.
Only the account key is cleared this way: a source which guessed one password right is not cleared of the failures it made on other accounts.
- Parameters:
key – The account key of the successful attempt
The policy file
- pelix.security.policy.normalize_fingerprint(fingerprint: str) → str
Normalizes a certificate fingerprint to the form of
fingerprint: lowercase hexadecimal, with no separator.Folding the case is safe here, unlike on a name: a fingerprint is a number, and its two spellings are the same value rather than two identities.
- Parameters:
fingerprint – A fingerprint, as
openssl x509 -fingerprint -sha256prints it or in any case, with or without:separators- Returns:
The normalized fingerprint
- Raises:
ValueError – This is not a SHA-256 fingerprint