-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauthentication.py
More file actions
217 lines (176 loc) · 7.02 KB
/
authentication.py
File metadata and controls
217 lines (176 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import inspect
import logging
from abc import ABC, abstractmethod
from functools import lru_cache
from logging import Logger
from typing import Any, Sequence, Type
from rodi import ContainerProtocol
from guardpost.abc import BaseStrategy
from guardpost.protection import InvalidCredentialsError, RateLimiter
class Identity:
"""
Represents the characteristics of a person or a thing in the context of an
application. It can be a user interacting with an app, or a technical account.
"""
def __init__(
self,
claims: dict | None = None,
authentication_mode: str | None = None,
):
self.claims = claims or {}
self.authentication_mode = authentication_mode
self.access_token: str | None = None
self.refresh_token: str | None = None
@property
def sub(self) -> str | None:
return self.get("sub")
@property
def roles(self) -> str | None:
return self.get("roles")
def is_authenticated(self) -> bool:
return bool(self.authentication_mode)
def get(self, key: str):
return self.claims.get(key)
def __getitem__(self, item):
return self.claims[item]
def has_claim(self, name: str) -> bool:
return name in self.claims
def has_claim_value(self, name: str, value: str) -> bool:
return self.claims.get(name) == value
def has_role(self, name: str) -> bool:
if not self.roles:
return False
return name in self.roles
class User(Identity):
@property
def id(self) -> str | None:
return self.get("id") or self.sub
@property
def name(self) -> str | None:
return self.get("name")
@property
def email(self) -> str | None:
return self.get("email")
class AuthenticationHandler(ABC):
"""Base class for types that implement authentication logic."""
@property
def scheme(self) -> str:
"""Returns the name of the Authentication Scheme used by this handler."""
return self.__class__.__name__
@abstractmethod
def authenticate(self, context: Any) -> Identity | None:
"""Obtains an identity from a context."""
@lru_cache(maxsize=None)
def _is_async_handler(handler_type: Type[AuthenticationHandler]) -> bool:
# Faster alternative to using inspect.iscoroutinefunction without caching
# Note: this must be used on Types - not instances!
return inspect.iscoroutinefunction(handler_type.authenticate)
AuthenticationHandlerConfType = AuthenticationHandler | Type[AuthenticationHandler]
class AuthenticationSchemesNotFound(ValueError):
def __init__(
self, configured_schemes: Sequence[str], required_schemes: Sequence[str]
):
super().__init__(
"Could not find authentication handlers for required schemes: "
f'{", ".join(required_schemes)}. '
f'Configured schemes are: {", ".join(configured_schemes)}'
)
class AuthenticationStrategy(BaseStrategy):
def __init__(
self,
*handlers: AuthenticationHandlerConfType,
container: ContainerProtocol | None = None,
rate_limiter: RateLimiter | None = None,
logger: Logger | None = None,
):
"""
Initializes an AuthenticationStrategy instance.
Args:
*handlers: One or more authentication handler instances or types to be used
for authentication.
container: Optional dependency injection container for resolving handler
instances.
rate_limiter: Optional RateLimiter to apply rate limiting to authentication
attempts.
logger: Optional logger instance for logging authentication events. If not
provided, defaults to `logging.getLogger("guardpost")`
"""
super().__init__(container)
self.handlers = list(handlers)
self._logger = logger or logging.getLogger("guardpost")
self._rate_limiter = rate_limiter
def add(self, handler: AuthenticationHandlerConfType) -> "AuthenticationStrategy":
self.handlers.append(handler)
return self
def __iadd__(
self, handler: AuthenticationHandlerConfType
) -> "AuthenticationStrategy":
self.handlers.append(handler)
return self
def _get_handlers_by_schemes(
self,
authentication_schemes: Sequence[str] | None = None,
context: Any = None,
) -> list[AuthenticationHandler]:
if not authentication_schemes:
return list(self._get_instances(self.handlers, context))
handlers = [
handler
for handler in self._get_instances(self.handlers, context)
if handler.scheme in authentication_schemes
]
if not handlers:
raise AuthenticationSchemesNotFound(
[
handler.scheme
for handler in self._get_instances(self.handlers, context)
],
authentication_schemes,
)
return handlers
async def authenticate(
self, context: Any, authentication_schemes: Sequence[str] | None = None
) -> Identity | None:
"""
Tries to obtain the user for a context, applying authentication rules and
optional rate limiting.
"""
if not context:
raise ValueError("Missing context to evaluate authentication")
if self._rate_limiter:
await self._rate_limiter.validate_authentication_attempt(context)
identity = None
for handler in self._get_handlers_by_schemes(authentication_schemes, context):
try:
identity = await self._authenticate_with_handler(handler, context)
except InvalidCredentialsError as invalid_credentials_error:
# A client provided credentials of a given type, and they were invalid.
# Store the information, so later calls can be validated without
# attempting authentication.
self._logger.info(
"Invalid credentials received from client IP %s for scheme: %s",
invalid_credentials_error.client_ip,
handler.scheme,
)
if self._rate_limiter:
await self._rate_limiter.store_authentication_failure(
invalid_credentials_error
)
if identity:
try:
context.identity = identity
except AttributeError:
pass
return identity
else:
try:
if context.identity is None:
context.identity = Identity()
except AttributeError:
pass
return None
async def _authenticate_with_handler(self, handler: AuthenticationHandler, context):
if _is_async_handler(type(handler)):
return await handler.authenticate(context) # type: ignore
else:
return handler.authenticate(context)