-
Notifications
You must be signed in to change notification settings - Fork 14.4k
/
manager.py
1751 lines (1495 loc) · 65.2 KB
/
manager.py
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# mypy: disable-error-code=var-annotated
from __future__ import annotations
import base64
import datetime
import json
import logging
from functools import cached_property
from typing import Any
from uuid import uuid4
import re2
from flask import Flask, current_app, g, session, url_for
from flask_appbuilder import AppBuilder
from flask_appbuilder.const import (
AUTH_DB,
AUTH_LDAP,
AUTH_OAUTH,
AUTH_OID,
AUTH_REMOTE_USER,
LOGMSG_ERR_SEC_ADD_REGISTER_USER,
LOGMSG_ERR_SEC_AUTH_LDAP,
LOGMSG_ERR_SEC_AUTH_LDAP_TLS,
LOGMSG_WAR_SEC_LOGIN_FAILED,
LOGMSG_WAR_SEC_NO_USER,
LOGMSG_WAR_SEC_NOLDAP_OBJ,
)
from flask_appbuilder.security.registerviews import (
RegisterUserDBView,
RegisterUserOAuthView,
RegisterUserOIDView,
)
from flask_appbuilder.security.views import (
AuthDBView,
AuthLDAPView,
AuthOAuthView,
AuthOIDView,
AuthRemoteUserView,
PermissionModelView,
RegisterUserModelView,
ResetMyPasswordView,
ResetPasswordView,
RoleModelView,
UserDBModelView,
UserInfoEditView,
UserLDAPModelView,
UserOAuthModelView,
UserOIDModelView,
UserRemoteUserModelView,
UserStatsChartView,
)
from flask_babel import lazy_gettext as _
from flask_jwt_extended import JWTManager, current_user as current_user_jwt
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_login import AnonymousUserMixin, LoginManager, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from airflow.configuration import auth_manager, conf
from airflow.www.fab_security.sqla.models import Action, Permission, RegisterUser, Resource, Role, User
# This product contains a modified portion of 'Flask App Builder' developed by Daniel Vaz Gaspar.
# (https://github.com/dpgaspar/Flask-AppBuilder).
# Copyright 2013, Daniel Vaz Gaspar
log = logging.getLogger(__name__)
def _oauth_tokengetter(token=None):
"""
Default function to return the current user oauth token
from session cookie.
"""
token = session.get("oauth")
log.debug("Token Get: %s", token)
return token
class AnonymousUser(AnonymousUserMixin):
"""User object used when no active user is logged in."""
_roles: set[tuple[str, str]] = set()
_perms: set[tuple[str, str]] = set()
@property
def roles(self):
if not self._roles:
public_role = current_app.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
self._roles = {current_app.appbuilder.sm.find_role(public_role)} if public_role else set()
return self._roles
@roles.setter
def roles(self, roles):
self._roles = roles
self._perms = set()
@property
def perms(self):
if not self._perms:
self._perms = set()
for role in self.roles:
self._perms.update({(perm.action.name, perm.resource.name) for perm in role.permissions})
return self._perms
class BaseSecurityManager:
"""Base class to define the Security Manager interface."""
appbuilder: AppBuilder
"""The appbuilder instance for the current security manager."""
auth_view = None
""" The obj instance for authentication view """
user_view = None
""" The obj instance for user view """
registeruser_view = None
""" The obj instance for registering user view """
lm = None
""" Flask-Login LoginManager """
jwt_manager = None
""" Flask-JWT-Extended """
oid = None
""" Flask-OpenID OpenID """
oauth = None
""" Flask-OAuth """
oauth_remotes: dict[str, Any]
""" OAuth email whitelists """
oauth_whitelists: dict[str, list] = {}
""" Initialized (remote_app) providers dict {'provider_name', OBJ } """
@staticmethod
def oauth_tokengetter(token=None):
"""Authentication (OAuth) token getter function.
Override to implement your own token getter method.
"""
return _oauth_tokengetter(token)
oauth_user_info = None
user_model: type[User]
""" Override to set your own User Model """
role_model: type[Role]
""" Override to set your own Role Model """
action_model: type[Action]
""" Override to set your own Action Model """
resource_model: type[Resource]
""" Override to set your own Resource Model """
permission_model: type[Permission]
""" Override to set your own Permission Model """
registeruser_model: type[RegisterUser]
""" Override to set your own RegisterUser Model """
userdbmodelview = UserDBModelView
""" Override if you want your own user db view """
userldapmodelview = UserLDAPModelView
""" Override if you want your own user ldap view """
useroidmodelview = UserOIDModelView
""" Override if you want your own user OID view """
useroauthmodelview = UserOAuthModelView
""" Override if you want your own user OAuth view """
userremoteusermodelview = UserRemoteUserModelView
""" Override if you want your own user REMOTE_USER view """
registerusermodelview = RegisterUserModelView
authdbview = AuthDBView
""" Override if you want your own Authentication DB view """
authldapview = AuthLDAPView
""" Override if you want your own Authentication LDAP view """
authoidview = AuthOIDView
""" Override if you want your own Authentication OID view """
authoauthview = AuthOAuthView
""" Override if you want your own Authentication OAuth view """
authremoteuserview = AuthRemoteUserView
""" Override if you want your own Authentication REMOTE_USER view """
registeruserdbview = RegisterUserDBView
""" Override if you want your own register user db view """
registeruseroidview = RegisterUserOIDView
""" Override if you want your own register user OpenID view """
registeruseroauthview = RegisterUserOAuthView
""" Override if you want your own register user OAuth view """
resetmypasswordview = ResetMyPasswordView
""" Override if you want your own reset my password view """
resetpasswordview = ResetPasswordView
""" Override if you want your own reset password view """
userinfoeditview = UserInfoEditView
""" Override if you want your own User information edit view """
rolemodelview = RoleModelView
actionmodelview = PermissionModelView
userstatschartview = UserStatsChartView
permissionmodelview = PermissionModelView
@cached_property
def resourcemodelview(self):
from airflow.www.views import ResourceModelView
return ResourceModelView
def __init__(self, appbuilder):
self.appbuilder = appbuilder
app = self.appbuilder.get_app
# Base Security Config
app.config.setdefault("AUTH_ROLE_ADMIN", "Admin")
app.config.setdefault("AUTH_ROLE_PUBLIC", "Public")
app.config.setdefault("AUTH_TYPE", AUTH_DB)
# Self Registration
app.config.setdefault("AUTH_USER_REGISTRATION", False)
app.config.setdefault("AUTH_USER_REGISTRATION_ROLE", self.auth_role_public)
app.config.setdefault("AUTH_USER_REGISTRATION_ROLE_JMESPATH", None)
# Role Mapping
app.config.setdefault("AUTH_ROLES_MAPPING", {})
app.config.setdefault("AUTH_ROLES_SYNC_AT_LOGIN", False)
app.config.setdefault("AUTH_API_LOGIN_ALLOW_MULTIPLE_PROVIDERS", False)
# LDAP Config
if self.auth_type == AUTH_LDAP:
if "AUTH_LDAP_SERVER" not in app.config:
raise Exception("No AUTH_LDAP_SERVER defined on config with AUTH_LDAP authentication type.")
app.config.setdefault("AUTH_LDAP_SEARCH", "")
app.config.setdefault("AUTH_LDAP_SEARCH_FILTER", "")
app.config.setdefault("AUTH_LDAP_APPEND_DOMAIN", "")
app.config.setdefault("AUTH_LDAP_USERNAME_FORMAT", "")
app.config.setdefault("AUTH_LDAP_BIND_USER", "")
app.config.setdefault("AUTH_LDAP_BIND_PASSWORD", "")
# TLS options
app.config.setdefault("AUTH_LDAP_USE_TLS", False)
app.config.setdefault("AUTH_LDAP_ALLOW_SELF_SIGNED", False)
app.config.setdefault("AUTH_LDAP_TLS_DEMAND", False)
app.config.setdefault("AUTH_LDAP_TLS_CACERTDIR", "")
app.config.setdefault("AUTH_LDAP_TLS_CACERTFILE", "")
app.config.setdefault("AUTH_LDAP_TLS_CERTFILE", "")
app.config.setdefault("AUTH_LDAP_TLS_KEYFILE", "")
# Mapping options
app.config.setdefault("AUTH_LDAP_UID_FIELD", "uid")
app.config.setdefault("AUTH_LDAP_GROUP_FIELD", "memberOf")
app.config.setdefault("AUTH_LDAP_FIRSTNAME_FIELD", "givenName")
app.config.setdefault("AUTH_LDAP_LASTNAME_FIELD", "sn")
app.config.setdefault("AUTH_LDAP_EMAIL_FIELD", "mail")
# Rate limiting
app.config.setdefault("AUTH_RATE_LIMITED", True)
app.config.setdefault("AUTH_RATE_LIMIT", "5 per 40 second")
if self.auth_type == AUTH_OID:
from flask_openid import OpenID
self.oid = OpenID(app)
if self.auth_type == AUTH_OAUTH:
from authlib.integrations.flask_client import OAuth
self.oauth = OAuth(app)
self.oauth_remotes = {}
for _provider in self.oauth_providers:
provider_name = _provider["name"]
log.debug("OAuth providers init %s", provider_name)
obj_provider = self.oauth.register(provider_name, **_provider["remote_app"])
obj_provider._tokengetter = self.oauth_tokengetter
if not self.oauth_user_info:
self.oauth_user_info = self.get_oauth_user_info
# Whitelist only users with matching emails
if "whitelist" in _provider:
self.oauth_whitelists[provider_name] = _provider["whitelist"]
self.oauth_remotes[provider_name] = obj_provider
self._builtin_roles = self.create_builtin_roles()
# Setup Flask-Login
self.lm = self.create_login_manager(app)
# Setup Flask-Jwt-Extended
self.jwt_manager = self.create_jwt_manager(app)
# Setup Flask-Limiter
self.limiter = self.create_limiter(app)
def create_limiter(self, app: Flask) -> Limiter:
limiter = Limiter(key_func=get_remote_address)
limiter.init_app(app)
return limiter
def create_login_manager(self, app) -> LoginManager:
"""
Override to implement your custom login manager instance.
:param app: Flask app
"""
lm = LoginManager(app)
lm.anonymous_user = AnonymousUser
lm.login_view = "login"
lm.user_loader(self.load_user)
return lm
def create_jwt_manager(self, app) -> JWTManager:
"""
Override to implement your custom JWT manager instance.
:param app: Flask app
"""
jwt_manager = JWTManager()
jwt_manager.init_app(app)
jwt_manager.user_lookup_loader(self.load_user_jwt)
return jwt_manager
def create_builtin_roles(self):
"""Returns FAB builtin roles."""
return self.appbuilder.get_app.config.get("FAB_ROLES", {})
def get_roles_from_keys(self, role_keys: list[str]) -> set[RoleModelView]:
"""
Construct a list of FAB role objects, from a list of keys.
NOTE:
- keys are things like: "LDAP group DNs" or "OAUTH group names"
- we use AUTH_ROLES_MAPPING to map from keys, to FAB role names
:param role_keys: the list of FAB role keys
:return: a list of RoleModelView
"""
_roles = set()
_role_keys = set(role_keys)
for role_key, fab_role_names in self.auth_roles_mapping.items():
if role_key in _role_keys:
for fab_role_name in fab_role_names:
fab_role = self.find_role(fab_role_name)
if fab_role:
_roles.add(fab_role)
else:
log.warning("Can't find role specified in AUTH_ROLES_MAPPING: %s", fab_role_name)
return _roles
@property
def auth_type_provider_name(self):
provider_to_auth_type = {AUTH_DB: "db", AUTH_LDAP: "ldap"}
return provider_to_auth_type.get(self.auth_type)
@property
def get_url_for_registeruser(self):
"""Gets the URL for Register User."""
return url_for(f"{self.registeruser_view.endpoint}.{self.registeruser_view.default_view}")
@property
def get_user_datamodel(self):
"""Gets the User data model."""
return self.user_view.datamodel
@property
def get_register_user_datamodel(self):
"""Gets the Register User data model."""
return self.registerusermodelview.datamodel
@property
def builtin_roles(self):
"""Get the builtin roles."""
return self._builtin_roles
@property
def api_login_allow_multiple_providers(self):
return self.appbuilder.get_app.config["AUTH_API_LOGIN_ALLOW_MULTIPLE_PROVIDERS"]
@property
def auth_type(self):
"""Get the auth type."""
return self.appbuilder.get_app.config["AUTH_TYPE"]
@property
def auth_username_ci(self):
"""Gets the auth username for CI."""
return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
@property
def auth_role_admin(self):
"""Gets the admin role."""
return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
@property
def auth_role_public(self):
"""Gets the public role."""
return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
@property
def auth_ldap_server(self):
"""Gets the LDAP server object."""
return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"]
@property
def auth_ldap_use_tls(self):
"""Should LDAP use TLS."""
return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
@property
def auth_user_registration(self):
"""Will user self registration be allowed."""
return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION"]
@property
def auth_user_registration_role(self):
"""The default user self registration role."""
return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
@property
def auth_user_registration_role_jmespath(self) -> str:
"""The JMESPATH role to use for user registration."""
return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE_JMESPATH"]
@property
def auth_roles_mapping(self) -> dict[str, list[str]]:
"""The mapping of auth roles."""
return self.appbuilder.get_app.config["AUTH_ROLES_MAPPING"]
@property
def auth_roles_sync_at_login(self) -> bool:
"""Should roles be synced at login."""
return self.appbuilder.get_app.config["AUTH_ROLES_SYNC_AT_LOGIN"]
@property
def auth_ldap_search(self):
"""LDAP search object."""
return self.appbuilder.get_app.config["AUTH_LDAP_SEARCH"]
@property
def auth_ldap_search_filter(self):
"""LDAP search filter."""
return self.appbuilder.get_app.config["AUTH_LDAP_SEARCH_FILTER"]
@property
def auth_ldap_bind_user(self):
"""LDAP bind user."""
return self.appbuilder.get_app.config["AUTH_LDAP_BIND_USER"]
@property
def auth_ldap_bind_password(self):
"""LDAP bind password."""
return self.appbuilder.get_app.config["AUTH_LDAP_BIND_PASSWORD"]
@property
def auth_ldap_append_domain(self):
"""LDAP append domain."""
return self.appbuilder.get_app.config["AUTH_LDAP_APPEND_DOMAIN"]
@property
def auth_ldap_username_format(self):
"""LDAP username format."""
return self.appbuilder.get_app.config["AUTH_LDAP_USERNAME_FORMAT"]
@property
def auth_ldap_uid_field(self):
"""LDAP UID field."""
return self.appbuilder.get_app.config["AUTH_LDAP_UID_FIELD"]
@property
def auth_ldap_group_field(self) -> str:
"""LDAP group field."""
return self.appbuilder.get_app.config["AUTH_LDAP_GROUP_FIELD"]
@property
def auth_ldap_firstname_field(self):
"""LDAP first name field."""
return self.appbuilder.get_app.config["AUTH_LDAP_FIRSTNAME_FIELD"]
@property
def auth_ldap_lastname_field(self):
"""LDAP last name field."""
return self.appbuilder.get_app.config["AUTH_LDAP_LASTNAME_FIELD"]
@property
def auth_ldap_email_field(self):
"""LDAP email field."""
return self.appbuilder.get_app.config["AUTH_LDAP_EMAIL_FIELD"]
@property
def auth_ldap_bind_first(self):
"""LDAP bind first."""
return self.appbuilder.get_app.config["AUTH_LDAP_BIND_FIRST"]
@property
def auth_ldap_allow_self_signed(self):
"""LDAP allow self signed."""
return self.appbuilder.get_app.config["AUTH_LDAP_ALLOW_SELF_SIGNED"]
@property
def auth_ldap_tls_demand(self):
"""LDAP TLS demand."""
return self.appbuilder.get_app.config["AUTH_LDAP_TLS_DEMAND"]
@property
def auth_ldap_tls_cacertdir(self):
"""LDAP TLS CA certificate directory."""
return self.appbuilder.get_app.config["AUTH_LDAP_TLS_CACERTDIR"]
@property
def auth_ldap_tls_cacertfile(self):
"""LDAP TLS CA certificate file."""
return self.appbuilder.get_app.config["AUTH_LDAP_TLS_CACERTFILE"]
@property
def auth_ldap_tls_certfile(self):
"""LDAP TLS certificate file."""
return self.appbuilder.get_app.config["AUTH_LDAP_TLS_CERTFILE"]
@property
def auth_ldap_tls_keyfile(self):
"""LDAP TLS key file."""
return self.appbuilder.get_app.config["AUTH_LDAP_TLS_KEYFILE"]
@property
def openid_providers(self):
"""Openid providers."""
return self.appbuilder.get_app.config["OPENID_PROVIDERS"]
@property
def oauth_providers(self):
"""Oauth providers."""
return self.appbuilder.get_app.config["OAUTH_PROVIDERS"]
@property
def is_auth_limited(self) -> bool:
return self.appbuilder.get_app.config["AUTH_RATE_LIMITED"]
@property
def auth_rate_limit(self) -> str:
return self.appbuilder.get_app.config["AUTH_RATE_LIMIT"]
@property
def current_user(self):
"""Current user object."""
if auth_manager.is_logged_in():
return g.user
elif current_user_jwt:
return current_user_jwt
def oauth_user_info_getter(self, f):
"""
Decorator function to be the OAuth user info getter
for all the providers, receives provider and response
return a dict with the information returned from the provider.
The returned user info dict should have it's keys with the same
name as the User Model.
Use it like this an example for GitHub ::
@appbuilder.sm.oauth_user_info_getter
def my_oauth_user_info(sm, provider, response=None):
if provider == 'github':
me = sm.oauth_remotes[provider].get('user')
return {'username': me.data.get('login')}
else:
return {}
"""
def wraps(provider, response=None):
ret = f(self, provider, response=response)
# Checks if decorator is well behaved and returns a dict as supposed.
if not type(ret) == dict:
log.error("OAuth user info decorated function did not returned a dict, but: %s", type(ret))
return {}
return ret
self.oauth_user_info = wraps
return wraps
def get_oauth_token_key_name(self, provider):
"""
Returns the token_key name for the oauth provider
if none is configured defaults to oauth_token
this is configured using OAUTH_PROVIDERS and token_key key.
"""
for _provider in self.oauth_providers:
if _provider["name"] == provider:
return _provider.get("token_key", "oauth_token")
def get_oauth_token_secret_name(self, provider):
"""Gety the ``token_secret`` name for the oauth provider.
If none is configured, defaults to ``oauth_secret``. This is configured
using ``OAUTH_PROVIDERS`` and ``token_secret``.
"""
for _provider in self.oauth_providers:
if _provider["name"] == provider:
return _provider.get("token_secret", "oauth_token_secret")
def set_oauth_session(self, provider, oauth_response):
"""Set the current session with OAuth user secrets."""
# Get this provider key names for token_key and token_secret
token_key = self.appbuilder.sm.get_oauth_token_key_name(provider)
token_secret = self.appbuilder.sm.get_oauth_token_secret_name(provider)
# Save users token on encrypted session cookie
session["oauth"] = (
oauth_response[token_key],
oauth_response.get(token_secret, ""),
)
session["oauth_provider"] = provider
def get_oauth_user_info(self, provider, resp):
"""Get the OAuth user information from different OAuth APIs.
All providers have different ways to retrieve user info.
"""
# for GITHUB
if provider == "github" or provider == "githublocal":
me = self.appbuilder.sm.oauth_remotes[provider].get("user")
data = me.json()
log.debug("User info from GitHub: %s", data)
return {"username": "github_" + data.get("login")}
# for twitter
if provider == "twitter":
me = self.appbuilder.sm.oauth_remotes[provider].get("account/settings.json")
data = me.json()
log.debug("User info from Twitter: %s", data)
return {"username": "twitter_" + data.get("screen_name", "")}
# for linkedin
if provider == "linkedin":
me = self.appbuilder.sm.oauth_remotes[provider].get(
"people/~:(id,email-address,first-name,last-name)?format=json"
)
data = me.json()
log.debug("User info from LinkedIn: %s", data)
return {
"username": "linkedin_" + data.get("id", ""),
"email": data.get("email-address", ""),
"first_name": data.get("firstName", ""),
"last_name": data.get("lastName", ""),
}
# for Google
if provider == "google":
me = self.appbuilder.sm.oauth_remotes[provider].get("userinfo")
data = me.json()
log.debug("User info from Google: %s", data)
return {
"username": "google_" + data.get("id", ""),
"first_name": data.get("given_name", ""),
"last_name": data.get("family_name", ""),
"email": data.get("email", ""),
}
# for Azure AD Tenant. Azure OAuth response contains
# JWT token which has user info.
# JWT token needs to be base64 decoded.
# https://docs.microsoft.com/en-us/azure/active-directory/develop/
# active-directory-protocols-oauth-code
if provider == "azure":
log.debug("Azure response received : %s", resp)
id_token = resp["id_token"]
log.debug(str(id_token))
me = self._azure_jwt_token_parse(id_token)
log.debug("Parse JWT token : %s", me)
return {
"name": me.get("name", ""),
"email": me["upn"],
"first_name": me.get("given_name", ""),
"last_name": me.get("family_name", ""),
"id": me["oid"],
"username": me["oid"],
"role_keys": me.get("roles", []),
}
# for OpenShift
if provider == "openshift":
me = self.appbuilder.sm.oauth_remotes[provider].get("apis/user.openshift.io/v1/users/~")
data = me.json()
log.debug("User info from OpenShift: %s", data)
return {"username": "openshift_" + data.get("metadata").get("name")}
# for Okta
if provider == "okta":
me = self.appbuilder.sm.oauth_remotes[provider].get("userinfo")
data = me.json()
log.debug("User info from Okta: %s", data)
return {
"username": "okta_" + data.get("sub", ""),
"first_name": data.get("given_name", ""),
"last_name": data.get("family_name", ""),
"email": data.get("email", ""),
"role_keys": data.get("groups", []),
}
# for Keycloak
if provider in ["keycloak", "keycloak_before_17"]:
me = self.appbuilder.sm.oauth_remotes[provider].get("openid-connect/userinfo")
me.raise_for_status()
data = me.json()
log.debug("User info from Keycloak: %s", data)
return {
"username": data.get("preferred_username", ""),
"first_name": data.get("given_name", ""),
"last_name": data.get("family_name", ""),
"email": data.get("email", ""),
}
else:
return {}
def _azure_parse_jwt(self, id_token):
jwt_token_parts = r"^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$"
matches = re2.search(jwt_token_parts, id_token)
if not matches or len(matches.groups()) < 3:
log.error("Unable to parse token.")
return {}
return {
"header": matches.group(1),
"Payload": matches.group(2),
"Sig": matches.group(3),
}
def _azure_jwt_token_parse(self, id_token):
jwt_split_token = self._azure_parse_jwt(id_token)
if not jwt_split_token:
return
jwt_payload = jwt_split_token["Payload"]
# Prepare for base64 decoding
payload_b64_string = jwt_payload
payload_b64_string += "=" * (4 - (len(jwt_payload) % 4))
decoded_payload = base64.urlsafe_b64decode(payload_b64_string.encode("ascii"))
if not decoded_payload:
log.error("Payload of id_token could not be base64 url decoded.")
return
jwt_decoded_payload = json.loads(decoded_payload.decode("utf-8"))
return jwt_decoded_payload
def register_views(self):
if not self.appbuilder.app.config.get("FAB_ADD_SECURITY_VIEWS", True):
return
if self.auth_user_registration:
if self.auth_type == AUTH_DB:
self.registeruser_view = self.registeruserdbview()
elif self.auth_type == AUTH_OID:
self.registeruser_view = self.registeruseroidview()
elif self.auth_type == AUTH_OAUTH:
self.registeruser_view = self.registeruseroauthview()
if self.registeruser_view:
self.appbuilder.add_view_no_menu(self.registeruser_view)
self.appbuilder.add_view_no_menu(self.resetpasswordview())
self.appbuilder.add_view_no_menu(self.resetmypasswordview())
self.appbuilder.add_view_no_menu(self.userinfoeditview())
if self.auth_type == AUTH_DB:
self.user_view = self.userdbmodelview
self.auth_view = self.authdbview()
elif self.auth_type == AUTH_LDAP:
self.user_view = self.userldapmodelview
self.auth_view = self.authldapview()
elif self.auth_type == AUTH_OAUTH:
self.user_view = self.useroauthmodelview
self.auth_view = self.authoauthview()
elif self.auth_type == AUTH_REMOTE_USER:
self.user_view = self.userremoteusermodelview
self.auth_view = self.authremoteuserview()
else:
self.user_view = self.useroidmodelview
self.auth_view = self.authoidview()
if self.auth_user_registration:
pass
# self.registeruser_view = self.registeruseroidview()
# self.appbuilder.add_view_no_menu(self.registeruser_view)
self.appbuilder.add_view_no_menu(self.auth_view)
# this needs to be done after the view is added, otherwise the blueprint
# is not initialized
if self.is_auth_limited:
self.limiter.limit(self.auth_rate_limit, methods=["POST"])(self.auth_view.blueprint)
self.user_view = self.appbuilder.add_view(
self.user_view,
"List Users",
icon="fa-user",
label=_("List Users"),
category="Security",
category_icon="fa-cogs",
category_label=_("Security"),
)
role_view = self.appbuilder.add_view(
self.rolemodelview,
"List Roles",
icon="fa-group",
label=_("List Roles"),
category="Security",
category_icon="fa-cogs",
)
role_view.related_views = [self.user_view.__class__]
if self.userstatschartview:
self.appbuilder.add_view(
self.userstatschartview,
"User's Statistics",
icon="fa-bar-chart-o",
label=_("User's Statistics"),
category="Security",
)
if self.auth_user_registration:
self.appbuilder.add_view(
self.registerusermodelview,
"User's Statistics",
icon="fa-user-plus",
label=_("User Registrations"),
category="Security",
)
self.appbuilder.menu.add_separator("Security")
if self.appbuilder.app.config.get("FAB_ADD_SECURITY_PERMISSION_VIEW", True):
self.appbuilder.add_view(
self.actionmodelview,
"Actions",
icon="fa-lock",
label=_("Actions"),
category="Security",
)
if self.appbuilder.app.config.get("FAB_ADD_SECURITY_VIEW_MENU_VIEW", True):
self.appbuilder.add_view(
self.resourcemodelview,
"Resources",
icon="fa-list-alt",
label=_("Resources"),
category="Security",
)
if self.appbuilder.app.config.get("FAB_ADD_SECURITY_PERMISSION_VIEWS_VIEW", True):
self.appbuilder.add_view(
self.permissionmodelview,
"Permission Pairs",
icon="fa-link",
label=_("Permissions"),
category="Security",
)
def create_db(self):
"""Setups the DB, creates admin and public roles if they don't exist."""
roles_mapping = self.appbuilder.get_app.config.get("FAB_ROLES_MAPPING", {})
for pk, name in roles_mapping.items():
self.update_role(pk, name)
for role_name in self.builtin_roles:
self.add_role(role_name)
if self.auth_role_admin not in self.builtin_roles:
self.add_role(self.auth_role_admin)
self.add_role(self.auth_role_public)
if self.count_users() == 0 and self.auth_role_public != self.auth_role_admin:
log.warning(LOGMSG_WAR_SEC_NO_USER)
def reset_password(self, userid, password):
"""
Change/Reset a user's password for authdb.
Password will be hashed and saved.
:param userid:
the user.id to reset the password
:param password:
The clear text password to reset and save hashed on the db
"""
user = self.get_user_by_id(userid)
user.password = generate_password_hash(password)
self.update_user(user)
def update_user_auth_stat(self, user, success=True):
"""Update user authentication stats.
This is done upon successful/unsuccessful authentication attempts.
:param user:
The identified (but possibly not successfully authenticated) user
model
:param success:
Defaults to true, if true increments login_count, updates
last_login, and resets fail_login_count to 0, if false increments
fail_login_count on user model.
"""
if not user.login_count:
user.login_count = 0
if not user.fail_login_count:
user.fail_login_count = 0
if success:
user.login_count += 1
user.last_login = datetime.datetime.now()
user.fail_login_count = 0
else:
user.fail_login_count += 1
self.update_user(user)
def _rotate_session_id(self):
"""Rotate the session ID.
We need to do this upon successful authentication when using the
database session backend.
"""
if conf.get("webserver", "SESSION_BACKEND") == "database":
session.sid = str(uuid4())
def auth_user_db(self, username, password):
"""
Method for authenticating user, auth db style.
:param username:
The username or registered email address
:param password:
The password, will be tested against hashed password on db
"""
if username is None or username == "":
return None
user = self.find_user(username=username)
if user is None:
user = self.find_user(email=username)
if user is None or (not user.is_active):
# Balance failure and success
check_password_hash(
"pbkdf2:sha256:150000$Z3t6fmj2$22da622d94a1f8118"
"c0976a03d2f18f680bfff877c9a965db9eedc51bc0be87c",
"password",
)
log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
return None
elif check_password_hash(user.password, password):
self._rotate_session_id()
self.update_user_auth_stat(user, True)
return user
else:
self.update_user_auth_stat(user, False)
log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
return None
def _search_ldap(self, ldap, con, username):
"""
Searches LDAP for user.
:param ldap: The ldap module reference
:param con: The ldap connection
:param username: username to match with AUTH_LDAP_UID_FIELD
:return: ldap object array
"""
# always check AUTH_LDAP_SEARCH is set before calling this method
assert self.auth_ldap_search, "AUTH_LDAP_SEARCH must be set"
# build the filter string for the LDAP search
if self.auth_ldap_search_filter:
filter_str = f"(&{self.auth_ldap_search_filter}({self.auth_ldap_uid_field}={username}))"
else:
filter_str = f"({self.auth_ldap_uid_field}={username})"
# build what fields to request in the LDAP search
request_fields = [
self.auth_ldap_firstname_field,
self.auth_ldap_lastname_field,
self.auth_ldap_email_field,
]
if len(self.auth_roles_mapping) > 0:
request_fields.append(self.auth_ldap_group_field)
# perform the LDAP search
log.debug(
"LDAP search for %r with fields %s in scope %r", filter_str, request_fields, self.auth_ldap_search
)
raw_search_result = con.search_s(
self.auth_ldap_search, ldap.SCOPE_SUBTREE, filter_str, request_fields
)
log.debug("LDAP search returned: %s", raw_search_result)
# Remove any search referrals from results
search_result = [
(dn, attrs) for dn, attrs in raw_search_result if dn is not None and isinstance(attrs, dict)
]
# only continue if 0 or 1 results were returned
if len(search_result) > 1:
log.error(
"LDAP search for %r in scope '%a' returned multiple results",
self.auth_ldap_search,
filter_str,
)
return None, None
try:
# extract the DN
user_dn = search_result[0][0]
# extract the other attributes
user_info = search_result[0][1]
# return
return user_dn, user_info
except (IndexError, NameError):
return None, None
def _ldap_calculate_user_roles(self, user_attributes: dict[str, list[bytes]]) -> list[str]:
user_role_objects = set()
# apply AUTH_ROLES_MAPPING
if len(self.auth_roles_mapping) > 0: