Debian Codegraph @

flask_security/tf_plugin.py

raw
1 """
2 flask_security.tf_plugin
3 ~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security Two-Factor Plugin Module
6
7 :copyright: (c) 2022-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 TODO:
11 - add localized callback for select choices.
12 """
13
14 from __future__ import annotations
15
16 import typing as t
17
18 from flask import request, redirect, session
19
20 from .decorators import unauth_csrf
21 from .forms import (
22 _build_form_from_request,
23 get_form_field_xlate,
24 Form,
25 RadioField,
26 SubmitField,
27 )
28 from .proxies import _datastore, _security
29 from .utils import (
30 _,
31 base_render_json,
32 check_and_get_token_status,
33 _config_value as cv,
34 do_flash,
35 get_message,
36 get_url,
37 login_user,
38 _propagate_next,
39 simple_render_json,
40 url_for_security,
41 )
42
43 if t.TYPE_CHECKING: # pragma: no cover
44 import flask
45 from flask.typing import ResponseValue
46 from flask import Response
47 from flask_security import Security, UserMixin
48
49
50 class TwoFactorSelectForm(Form):
51 which: RadioField = RadioField(
52 get_form_field_xlate(_("Available Second Factor Methods:"))
53 )
54 submit: SubmitField = SubmitField(get_form_field_xlate(_("Select")))
55
56 def __init__(self, *args: t.Any, **kwargs: t.Any):
57 super().__init__(*args, **kwargs)
58
59
60 @unauth_csrf()
61 def tf_select() -> ResponseValue:
62 # Ask user which MFA method they want to use.
63 # This is used when a user has setup more than one type of 2FA.
64 form = t.cast(
65 TwoFactorSelectForm, _build_form_from_request("two_factor_select_form")
66 )
67
68 # This endpoint is unauthenticated - make sure we're in a valid state
69 if not all(k in session for k in ["tf_user_id", "tf_select"]):
70 # illegal call on this endpoint
71 tf_clean_session()
72 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
73
74 user = _datastore.find_user(fs_uniquifier=session["tf_user_id"])
75 if not user: # pragma no cover
76 # hard to imagine - someone deletes the user while they are logging in.
77 tf_clean_session()
78 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
79
80 setup_methods = _security.two_factor_plugins.get_setup_tf_methods(user)
81 form.which.choices = setup_methods # type: ignore[assignment]
82
83 if form.validate_on_submit():
84 response = None
85 tf_impl = _security.two_factor_plugins.method_to_impl(user, form.which.data)
86 if tf_impl:
87 json_payload = {"tf_required": True}
88 response = tf_impl.tf_login(
89 user, json_payload, next_loc=_propagate_next(request.url, None)
90 )
91 if not response: # pragma no cover
92 # This really can't happen unless between the time the started logging in
93 # and now, they deleted a second factor (which they would have to do
94 # in another window).
95 tf_clean_session()
96 return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW"))
97 return response
98
99 if _security._want_json(request):
100 payload = {"tf_select": True, "tf_setup_methods": [k for k, v in setup_methods]}
101 return base_render_json(form, include_user=False, additional=payload)
102
103 return _security.render_template(
104 cv("TWO_FACTOR_SELECT_TEMPLATE"),
105 two_factor_select_form=form,
106 **_security._run_ctx_processor("tf_select"),
107 )
108
109
110 class TfPluginBase: # pragma no cover
111 def __init__(self, app: flask.Flask):
112 pass
113
114 def create_blueprint(
115 self, app: flask.Flask, bp: flask.Blueprint, state: Security
116 ) -> None:
117 raise NotImplementedError
118
119 def get_setup_methods(self, user: UserMixin) -> list[tuple[str, str]]:
120 """Return a list of tuples representing currently configured methods.
121 The tuple is (value, label) - suitable for use in a FlaskForm Select element.
122 """
123 raise NotImplementedError
124
125 def tf_login(
126 self, user: UserMixin, json_payload: dict[str, t.Any], next_loc: str | None
127 ) -> ResponseValue:
128 """
129 Called from first/primary authenticated views if the user successfully
130 authenticated, and required a second method of authentication.
131 This method returns the necessary information for the user UI to continue.
132 For forms, this is usually a redirect to a secondary sign in form. For JSON
133 it is just a payload that describes what the user has to do next.
134 """
135 raise NotImplementedError
136
137
138 class TfPlugin:
139 """
140 Two-Factor plugin support.
141
142 Enables multiple independent two-factor implementations to be configured for a given
143 app. See TfPluginBase for what a new implementation must provide.
144 """
145
146 def __init__(self) -> None:
147 self._tf_impls: dict[str, TfPluginBase] = {}
148
149 def register_tf_impl(
150 # N.B. all methods must be unique across all implementations.
151 self,
152 app: flask.Flask,
153 name: str,
154 impl: t.Type[TfPluginBase],
155 ) -> None:
156 self._tf_impls[name] = impl(app)
157
158 def create_blueprint(
159 self, app: flask.Flask, bp: flask.Blueprint, state: Security
160 ) -> None:
161 if state.support_mfa:
162 for impl in self._tf_impls.values():
163 impl.create_blueprint(app, bp, state)
164 # Add our route for selecting between multiple active two-factor
165 # mechanisms.
166 bp.route(
167 cv("TWO_FACTOR_SELECT_URL", app),
168 methods=["GET", "POST"],
169 endpoint="tf_select",
170 )(tf_select)
171
172 def method_to_impl(self, user: UserMixin, method: str) -> TfPluginBase | None:
173 # reverse map a method to the implementation.
174 # N.B. again - requires that methods be unique across all implementations.
175 # There is a small window that a previously setup method was removed.
176 for impl in self._tf_impls.values():
177 setup_methods = impl.get_setup_methods(user)
178 if method in [k for k, v in setup_methods]:
179 return impl
180 return None # pragma no cover
181
182 def get_setup_tf_methods(self, user: UserMixin) -> list[tuple[str, str]]:
183 """Return a list of tuples representing currently configured methods.
184 The tuple is (value, translated(value)) - suitable for use in a
185 FlaskForm Select element.
186 """
187 methods = []
188 for impl in self._tf_impls.values():
189 methods.extend(impl.get_setup_methods(user))
190 return methods
191
192 def tf_enter(
193 self,
194 user: UserMixin,
195 remember_me: bool | None,
196 primary_authn_via: str,
197 next_loc: str | None,
198 ) -> ResponseValue | None:
199 """Check if two-factor is required and if so, start the process.
200 Must be called in a request context.
201 remember_me controls 2 cookies - the remember_me cookie and the tf_validity
202 cookie. We use the session to hold the fact that the user requested 'remember'
203 across the second factor.
204 """
205 json_payload: dict[str, t.Any]
206 if _security.support_mfa:
207 tf_setup_methods = self.get_setup_tf_methods(user)
208 tf_fresh = tf_verify_validity_token(user.fs_uniquifier)
209 tf_required, tf_available_methods = user.check_tf_required(
210 tf_setup_methods, tf_fresh
211 )
212 if tf_required:
213 tf_setup_methods_keys = [t1 for t1, t2 in tf_setup_methods]
214 # Clean out any potential old session info - in case of previous
215 # aborted 2FA attempt.
216 tf_clean_session()
217
218 json_payload = {"tf_required": True}
219 if remember_me:
220 session["tf_remember_login"] = remember_me
221
222 session["tf_user_id"] = user.fs_uniquifier
223 # A backwards compat hack - the original twofactor could be setup
224 # as part of initial login.
225 if len(tf_setup_methods) == 0:
226 # only initial two-factor implementation supports this
227 return self._tf_impls["code"].tf_login(user, json_payload, next_loc)
228 elif len(tf_setup_methods) == 1:
229 # method_to_impl can't return None here since we just
230 # got the methods up above.
231 impl = t.cast(
232 TfPluginBase,
233 self.method_to_impl(user, tf_setup_methods_keys[0]),
234 )
235 return impl.tf_login(user, json_payload, next_loc)
236 else:
237 session["tf_select"] = True
238 if not _security._want_json(request):
239 values = dict(next=next_loc) if next_loc else dict()
240 return redirect(url_for_security("tf_select", **values))
241 # Let's force app to go through tf-select just in case we want
242 # to do further validation... However, provide the choices
243 # so they can just do a POST
244 json_payload.update(
245 {
246 "tf_select": True,
247 "tf_setup_methods": tf_setup_methods_keys,
248 }
249 )
250 return simple_render_json(json_payload)
251 return None
252
253 def tf_complete(self, user: UserMixin, dologin: bool) -> str | None:
254 remember = session.pop("tf_remember_login", None)
255
256 if dologin:
257 login_user(user, remember=remember)
258 tf_clean_session()
259 token = None
260 # return a token to avoid future two-factor prompts (for a period of time)
261 if not cv("TWO_FACTOR_ALWAYS_VALIDATE") and remember:
262 token = generate_tf_validity_token(user.fs_uniquifier)
263 return token
264
265
266 def generate_tf_validity_token(fs_uniquifier):
267 """Generates a unique token for the specified user.
268
269 :param fs_uniquifier: The fs_uniquifier of a user to whom the token belongs to
270 """
271 return _security.tf_validity_serializer.dumps(fs_uniquifier)
272
273
274 def tf_validity_token_status(token):
275 """Returns the expired status, invalid status, and user of a
276 Two-Factor Validity token.
277 For example::
278
279 expired, invalid, user = tf_validity_token_status('...')
280
281 :param token: The Two-Factor Validity token
282 """
283 return check_and_get_token_status(
284 token, "tf_validity", cv("TWO_FACTOR_LOGIN_VALIDITY")
285 )
286
287
288 def tf_verify_validity_token(fs_uniquifier: str) -> bool:
289 """Returns the status of the Two-Factor Validity token based on the current
290 request.
291
292 :param fs_uniquifier: The ``fs_uniquifier`` of the submitting user.
293 """
294 token = request.cookies.get(cv("TWO_FACTOR_VALIDITY_COOKIE_NAME"), default=None)
295 if token is None:
296 return False
297
298 expired, invalid, uniquifier = tf_validity_token_status(token)
299 if expired or invalid or (fs_uniquifier != uniquifier):
300 return False
301
302 return True
303
304
305 def tf_set_validity_token_cookie(response: Response, token: str) -> Response:
306 """Sets the Two-Factor validity cookie"""
307 cookie_kwargs = cv("TWO_FACTOR_VALIDITY_COOKIE")
308 max_age = int(cv("TWO_FACTOR_LOGIN_VALIDITY").total_seconds())
309 response.set_cookie(
310 cv("TWO_FACTOR_VALIDITY_COOKIE_NAME"),
311 value=token,
312 max_age=max_age,
313 **cookie_kwargs,
314 )
315 # This is likely overkill since so far we only return this on a POST which is
316 # unlikely to be cached.
317 response.vary.add("Cookie")
318 return response
319
320
321 def tf_check_state(allowed_states: list[str]) -> UserMixin | None:
322 if (
323 not all(k in session for k in ["tf_user_id", "tf_state"])
324 or session["tf_state"] not in allowed_states
325 ):
326 tf_clean_session()
327 return None
328
329 user = _datastore.find_user(fs_uniquifier=session["tf_user_id"])
330 if not user:
331 tf_clean_session()
332 return user
333
334
335 def tf_illegal_state(form, redirect_to):
336 m, c = get_message("TWO_FACTOR_PERMISSION_DENIED")
337 if not _security._want_json(request):
338 do_flash(m, c)
339 return redirect(get_url(redirect_to))
340 else:
341 form.form_errors.append(m)
342 return base_render_json(form, include_user=False)
343
344
345 def tf_clean_session():
346 """
347 Clean out ALL stuff stored in session (e.g. on logout or restart of a session)
348 """
349 if cv("TWO_FACTOR"):
350 for k in [
351 "tf_state",
352 "tf_user_id",
353 "tf_primary_method",
354 "tf_remember_login",
355 "tf_totp_secret",
356 "tf_select",
357 ]:
358 session.pop(k, None)