-
Notifications
You must be signed in to change notification settings - Fork 14.5k
/
override.py
2677 lines (2339 loc) · 105 KB
/
override.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.
from __future__ import annotations
import datetime
import itertools
import logging
import os
import random
import uuid
import warnings
from typing import TYPE_CHECKING, Any, Callable, Collection, Container, Iterable, Sequence
import jwt
import re2
from flask import flash, g, has_request_context, session
from flask_appbuilder import const
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_NOLDAP_OBJ,
MICROSOFT_KEY_SET_URL,
)
from flask_appbuilder.models.sqla import Base
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.registerviews import (
RegisterUserDBView,
RegisterUserOAuthView,
RegisterUserOIDView,
)
from flask_appbuilder.security.views import (
AuthDBView,
AuthLDAPView,
AuthOAuthView,
AuthOIDView,
AuthRemoteUserView,
RegisterUserModelView,
)
from flask_babel import lazy_gettext
from flask_jwt_extended import JWTManager, current_user as current_user_jwt
from flask_login import LoginManager
from itsdangerous import want_bytes
from markupsafe import Markup
from sqlalchemy import and_, func, inspect, literal, or_, select
from sqlalchemy.exc import MultipleResultsFound
from sqlalchemy.orm import Session, joinedload
from werkzeug.security import check_password_hash, generate_password_hash
from airflow.auth.managers.utils.fab import get_method_from_fab_action_map
from airflow.configuration import conf
from airflow.exceptions import AirflowException, AirflowProviderDeprecationWarning, RemovedInAirflow3Warning
from airflow.models import DagBag, DagModel
from airflow.providers.fab.auth_manager.models import (
Action,
Permission,
RegisterUser,
Resource,
Role,
User,
assoc_permission_role,
)
from airflow.providers.fab.auth_manager.models.anonymous_user import AnonymousUser
from airflow.providers.fab.auth_manager.security_manager.constants import EXISTING_ROLES
from airflow.providers.fab.auth_manager.views.permissions import (
ActionModelView,
PermissionPairModelView,
ResourceModelView,
)
from airflow.providers.fab.auth_manager.views.roles_list import CustomRoleModelView
from airflow.providers.fab.auth_manager.views.user import (
CustomUserDBModelView,
CustomUserLDAPModelView,
CustomUserOAuthModelView,
CustomUserOIDModelView,
CustomUserRemoteUserModelView,
)
from airflow.providers.fab.auth_manager.views.user_edit import (
CustomResetMyPasswordView,
CustomResetPasswordView,
CustomUserInfoEditView,
)
from airflow.providers.fab.auth_manager.views.user_stats import CustomUserStatsChartView
from airflow.security import permissions
from airflow.utils.session import NEW_SESSION, provide_session
from airflow.www.extensions.init_auth_manager import get_auth_manager
from airflow.www.security_manager import AirflowSecurityManagerV2
from airflow.www.session import AirflowDatabaseSessionInterface
if TYPE_CHECKING:
from airflow.auth.managers.base_auth_manager import ResourceMethod
log = logging.getLogger(__name__)
# This is the limit of DB user sessions that we consider as "healthy". If you have more sessions that this
# number then we will refuse to delete sessions that have expired and old user sessions when resetting
# user's password, and raise a warning in the UI instead. Usually when you have that many sessions, it means
# that there is something wrong with your deployment - for example you have an automated API call that
# continuously creates new sessions. Such setup should be fixed by reusing sessions or by periodically
# purging the old sessions by using `airflow db clean` command.
MAX_NUM_DATABASE_USER_SESSIONS = 50000
class FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
"""
This security manager overrides the default AirflowSecurityManager security manager.
This security manager is used only if the auth manager FabAuthManager is used. It defines everything in
the security manager that is needed for the FabAuthManager to work. Any operation specific to
the AirflowSecurityManager should be defined here instead of AirflowSecurityManager.
:param appbuilder: The appbuilder.
"""
auth_view = None
""" The obj instance for authentication view """
registeruser_view = None
""" The obj instance for registering user view """
user_view = None
""" The obj instance for user view """
""" Models """
user_model = User
role_model = Role
action_model = Action
resource_model = Resource
permission_model = Permission
""" Views """
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 """
actionmodelview = ActionModelView
permissionmodelview = PermissionPairModelView
rolemodelview = CustomRoleModelView
registeruser_model = RegisterUser
registerusermodelview = RegisterUserModelView
resourcemodelview = ResourceModelView
userdbmodelview = CustomUserDBModelView
resetmypasswordview = CustomResetMyPasswordView
resetpasswordview = CustomResetPasswordView
userinfoeditview = CustomUserInfoEditView
userldapmodelview = CustomUserLDAPModelView
useroauthmodelview = CustomUserOAuthModelView
userremoteusermodelview = CustomUserRemoteUserModelView
useroidmodelview = CustomUserOIDModelView
userstatschartview = CustomUserStatsChartView
jwt_manager = None
""" Flask-JWT-Extended """
oid = None
""" Flask-OpenID OpenID """
oauth = None
oauth_remotes: dict[str, Any]
""" Initialized (remote_app) providers dict {'provider_name', OBJ } """
oauth_user_info = None
oauth_allow_list: dict[str, list] = {}
""" OAuth email allow list """
# global resource for dag-level access
DAG_RESOURCES = {permissions.RESOURCE_DAG}
###########################################################################
# PERMISSIONS
###########################################################################
# [START security_viewer_perms]
VIEWER_PERMISSIONS = [
(permissions.ACTION_CAN_READ, permissions.RESOURCE_AUDIT_LOG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_DEPENDENCIES),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_CODE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DATASET),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_CLUSTER_ACTIVITY),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_WARNING),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_JOB),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_MY_PASSWORD),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_MY_PASSWORD),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_MY_PROFILE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_MY_PROFILE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_PLUGIN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_SLA_MISS),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_LOG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_WEBSITE),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_BROWSE_MENU),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG_DEPENDENCIES),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DATASET),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_CLUSTER_ACTIVITY),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DOCS),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_DOCS_MENU),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_JOB),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_AUDIT_LOG),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_PLUGIN),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_SLA_MISS),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_TASK_INSTANCE),
]
# [END security_viewer_perms]
# [START security_user_perms]
USER_PERMISSIONS = [
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_DAG_RUN),
]
# [END security_user_perms]
# [START security_op_perms]
OP_PERMISSIONS = [
(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONFIG),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_ADMIN_MENU),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_CONFIG),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_CONNECTION),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_PROVIDER),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_XCOM),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONNECTION),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONNECTION),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_CONNECTION),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_CONNECTION),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_POOL),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_PROVIDER),
(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_VARIABLE),
(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_XCOM),
]
# [END security_op_perms]
# [START security_admin_perms]
ADMIN_PERMISSIONS = [
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_RESCHEDULE),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_TASK_RESCHEDULE),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TRIGGER),
(permissions.ACTION_CAN_ACCESS_MENU, permissions.RESOURCE_TRIGGER),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_PASSWORD),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_PASSWORD),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_ROLE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_ROLE),
]
# [END security_admin_perms]
###########################################################################
# DEFAULT ROLE CONFIGURATIONS
###########################################################################
ROLE_CONFIGS: list[dict[str, Any]] = [
{"role": "Public", "perms": []},
{"role": "Viewer", "perms": VIEWER_PERMISSIONS},
{
"role": "User",
"perms": VIEWER_PERMISSIONS + USER_PERMISSIONS,
},
{
"role": "Op",
"perms": VIEWER_PERMISSIONS + USER_PERMISSIONS + OP_PERMISSIONS,
},
{
"role": "Admin",
"perms": VIEWER_PERMISSIONS + USER_PERMISSIONS + OP_PERMISSIONS + ADMIN_PERMISSIONS,
},
]
# global resource for dag-level access
DAG_ACTIONS = permissions.DAG_ACTIONS
def __init__(self, appbuilder):
# done in super, but we need it before we can call super.
self.appbuilder = appbuilder
self._init_config()
self._init_auth()
self._init_data_model()
# can only call super once data model init has been done
# because of the view.datamodel hack that's done in the init there.
super().__init__(appbuilder=appbuilder)
self._builtin_roles: dict = self.create_builtin_roles()
self.create_db()
# Setup Flask login
self.lm = self.create_login_manager()
# Setup Flask-Jwt-Extended
self.create_jwt_manager()
def register_views(self):
"""Register FAB auth manager related views."""
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()
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=lazy_gettext("List Users"),
category="Security",
category_icon="fa-cogs",
category_label=lazy_gettext("Security"),
)
role_view = self.appbuilder.add_view(
self.rolemodelview,
"List Roles",
icon="fa-group",
label=lazy_gettext("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=lazy_gettext("User's Statistics"),
category="Security",
)
if self.auth_user_registration:
self.appbuilder.add_view(
self.registerusermodelview,
"User's Statistics",
icon="fa-user-plus",
label=lazy_gettext("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=lazy_gettext("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=lazy_gettext("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=lazy_gettext("Permissions"),
category="Security",
)
@property
def get_session(self):
return self.appbuilder.get_session
def create_login_manager(self) -> LoginManager:
"""Create the login manager."""
lm = LoginManager(self.appbuilder.app)
lm.anonymous_user = AnonymousUser
lm.login_view = "login"
lm.user_loader(self.load_user)
return lm
def create_jwt_manager(self):
"""Create the JWT manager."""
jwt_manager = JWTManager()
jwt_manager.init_app(self.appbuilder.app)
jwt_manager.user_lookup_loader(self.load_user_jwt)
def reset_password(self, userid, password):
"""
Change/Reset a user's password for auth db.
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.reset_user_sessions(user)
self.update_user(user)
def reset_user_sessions(self, user: User) -> None:
if isinstance(self.appbuilder.get_app.session_interface, AirflowDatabaseSessionInterface):
interface = self.appbuilder.get_app.session_interface
session = interface.db.session
user_session_model = interface.sql_session_model
num_sessions = session.query(user_session_model).count()
if num_sessions > MAX_NUM_DATABASE_USER_SESSIONS:
self._cli_safe_flash(
f"The old sessions for user {user.username} have <b>NOT</b> been deleted!<br>"
f"You have a lot ({num_sessions}) of user sessions in the 'SESSIONS' table in "
f"your database.<br> "
"This indicates that this deployment might have an automated API calls that create "
"and not reuse sessions.<br>You should consider reusing sessions or cleaning them "
"periodically using db clean.<br>"
"Make sure to reset password for the user again after cleaning the session table "
"to remove old sessions of the user.",
"warning",
)
else:
for s in session.query(user_session_model):
session_details = interface.serializer.loads(want_bytes(s.data))
if session_details.get("_user_id") == user.id:
session.delete(s)
else:
self._cli_safe_flash(
"Since you are using `securecookie` session backend mechanism, we cannot prevent "
f"some old sessions for user {user.username} to be reused.<br> If you want to make sure "
"that the user is logged out from all sessions, you should consider using "
"`database` session backend mechanism.<br> You can also change the 'secret_key` "
"webserver configuration for all your webserver instances and restart the webserver. "
"This however will logout all users from all sessions.",
"warning",
)
def load_user_jwt(self, _jwt_header, jwt_data):
identity = jwt_data["sub"]
user = self.load_user(identity)
# Set flask g.user to JWT user, we can't do it on before request
g.user = user
return user
@property
def auth_type(self):
"""Get the auth type."""
return self.appbuilder.app.config["AUTH_TYPE"]
@property
def is_auth_limited(self) -> bool:
"""Is the auth rate limited."""
return self.appbuilder.app.config["AUTH_RATE_LIMITED"]
@property
def auth_rate_limit(self) -> str:
"""Get the auth rate limit."""
return self.appbuilder.app.config["AUTH_RATE_LIMIT"]
@property
def auth_role_public(self):
"""Gets the public role."""
return self.appbuilder.app.config["AUTH_ROLE_PUBLIC"]
@property
def oauth_providers(self):
"""Oauth providers."""
return self.appbuilder.app.config["OAUTH_PROVIDERS"]
@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 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_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_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_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_uid_field(self):
"""LDAP UID field."""
return self.appbuilder.get_app.config["AUTH_LDAP_UID_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_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_group_field(self) -> str:
"""LDAP group field."""
return self.appbuilder.get_app.config["AUTH_LDAP_GROUP_FIELD"]
@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_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 api_login_allow_multiple_providers(self):
return self.appbuilder.get_app.config["AUTH_API_LOGIN_ALLOW_MULTIPLE_PROVIDERS"]
@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_ldap_bind_first(self):
"""LDAP bind first."""
return self.appbuilder.get_app.config["AUTH_LDAP_BIND_FIRST"]
@property
def openid_providers(self):
"""Openid providers."""
return self.appbuilder.get_app.config["OPENID_PROVIDERS"]
@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 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_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_role_admin(self):
"""Gets the admin role."""
return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
@property
def oauth_whitelists(self):
warnings.warn(
"The 'oauth_whitelists' property is deprecated. Please use 'oauth_allow_list' instead.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
return self.oauth_allow_list
def create_builtin_roles(self):
"""Returns FAB builtin roles."""
return self.appbuilder.app.config.get("FAB_ROLES", {})
@property
def builtin_roles(self):
"""Get the builtin roles."""
return self._builtin_roles
def create_admin_standalone(self) -> tuple[str | None, str | None]:
"""Create an Admin user with a random password so that users can access airflow."""
from airflow.configuration import AIRFLOW_HOME, make_group_other_inaccessible
user_name = "admin"
# We want a streamlined first-run experience, but we do not want to
# use a preset password as people will inevitably run this on a public
# server. Thus, we make a random password and store it in AIRFLOW_HOME,
# with the reasoning that if you can read that directory, you can see
# the database credentials anyway.
password_path = os.path.join(AIRFLOW_HOME, "standalone_admin_password.txt")
user_exists = self.find_user(user_name) is not None
we_know_password = os.path.isfile(password_path)
# If the user does not exist, make a random password and make it
if not user_exists:
print(f"FlaskAppBuilder Authentication Manager: Creating {user_name} user")
role = self.find_role("Admin")
assert role is not None
# password does not contain visually similar characters: ijlIJL1oO0
password = "".join(random.choices("abcdefghkmnpqrstuvwxyzABCDEFGHKMNPQRSTUVWXYZ23456789", k=16))
with open(password_path, "w") as file:
file.write(password)
make_group_other_inaccessible(password_path)
self.add_user(user_name, "Admin", "User", "[email protected]", role, password)
print(f"FlaskAppBuilder Authentication Manager: Created {user_name} user")
# If the user does exist, and we know its password, read the password
elif user_exists and we_know_password:
with open(password_path) as file:
password = file.read().strip()
# Otherwise we don't know the password
else:
password = None
return user_name, password
def _init_config(self):
"""
Initialize config.
:meta private:
"""
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")
def _init_auth(self):
"""
Initialize authentication configuration.
:meta private:
"""
app = self.appbuilder.get_app
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_token_getter
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_allow_list[provider_name] = provider["whitelist"]
self.oauth_remotes[provider_name] = obj_provider
def _init_data_model(self):
user_data_model = SQLAInterface(self.user_model)
if self.auth_type == const.AUTH_DB:
self.userdbmodelview.datamodel = user_data_model
elif self.auth_type == const.AUTH_LDAP:
self.userldapmodelview.datamodel = user_data_model
elif self.auth_type == const.AUTH_OID:
self.useroidmodelview.datamodel = user_data_model
elif self.auth_type == const.AUTH_OAUTH:
self.useroauthmodelview.datamodel = user_data_model
elif self.auth_type == const.AUTH_REMOTE_USER:
self.userremoteusermodelview.datamodel = user_data_model
if self.userstatschartview:
self.userstatschartview.datamodel = user_data_model
if self.auth_user_registration:
self.registerusermodelview.datamodel = SQLAInterface(self.registeruser_model)
self.rolemodelview.datamodel = SQLAInterface(self.role_model)
self.actionmodelview.datamodel = SQLAInterface(self.action_model)
self.resourcemodelview.datamodel = SQLAInterface(self.resource_model)
self.permissionmodelview.datamodel = SQLAInterface(self.permission_model)
def create_db(self):
"""
Create the database.
Creates admin and public roles if they don't exist.
"""
if not self.appbuilder.update_perms:
log.debug("Skipping db since appbuilder disables update_perms")
return
try:
engine = self.get_session.get_bind(mapper=None, clause=None)
inspector = inspect(engine)
if "ab_user" not in inspector.get_table_names():
log.info(const.LOGMSG_INF_SEC_NO_DB)
Base.metadata.create_all(engine)
log.info(const.LOGMSG_INF_SEC_ADD_DB)
roles_mapping = self.appbuilder.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(const.LOGMSG_WAR_SEC_NO_USER)
except Exception as e:
log.error(const.LOGMSG_ERR_SEC_CREATE_DB, e)
exit(1)
def get_readable_dags(self, user) -> Iterable[DagModel]:
"""Get the DAGs readable by authenticated user."""
warnings.warn(
"`get_readable_dags` has been deprecated. Please use `get_auth_manager().get_permitted_dag_ids` "
"instead.",
RemovedInAirflow3Warning,
stacklevel=2,
)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RemovedInAirflow3Warning)
return self.get_accessible_dags([permissions.ACTION_CAN_READ], user)
def get_editable_dags(self, user) -> Iterable[DagModel]:
"""Get the DAGs editable by authenticated user."""
warnings.warn(
"`get_editable_dags` has been deprecated. Please use `get_auth_manager().get_permitted_dag_ids` "
"instead.",
RemovedInAirflow3Warning,
stacklevel=2,
)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RemovedInAirflow3Warning)
return self.get_accessible_dags([permissions.ACTION_CAN_EDIT], user)
@provide_session
def get_accessible_dags(
self,
user_actions: Container[str] | None,
user,
session: Session = NEW_SESSION,
) -> Iterable[DagModel]:
warnings.warn(
"`get_accessible_dags` has been deprecated. Please use "
"`get_auth_manager().get_permitted_dag_ids` instead.",
RemovedInAirflow3Warning,
stacklevel=3,
)
dag_ids = self.get_accessible_dag_ids(user, user_actions, session)
return session.scalars(select(DagModel).where(DagModel.dag_id.in_(dag_ids)))
@provide_session
def get_accessible_dag_ids(
self,
user,
user_actions: Container[str] | None = None,
session: Session = NEW_SESSION,
) -> set[str]:
warnings.warn(
"`get_accessible_dag_ids` has been deprecated. Please use "
"`get_auth_manager().get_permitted_dag_ids` instead.",
RemovedInAirflow3Warning,
stacklevel=3,
)
if not user_actions:
user_actions = [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]
method_from_fab_action_map = get_method_from_fab_action_map()
user_methods: Container[ResourceMethod] = [
method_from_fab_action_map[action]
for action in method_from_fab_action_map
if action in user_actions
]
return get_auth_manager().get_permitted_dag_ids(user=user, methods=user_methods, session=session)
@staticmethod
def get_readable_dag_ids(user=None) -> set[str]:
"""Get the DAG IDs readable by authenticated user."""
return get_auth_manager().get_permitted_dag_ids(methods=["GET"], user=user)
@staticmethod
def get_editable_dag_ids(user=None) -> set[str]:
"""Get the DAG IDs editable by authenticated user."""
return get_auth_manager().get_permitted_dag_ids(methods=["PUT"], user=user)
def can_access_some_dags(self, action: str, dag_id: str | None = None) -> bool:
"""Check if user has read or write access to some dags."""
if dag_id and dag_id != "~":
root_dag_id = self._get_root_dag_id(dag_id)
return self.has_access(action, permissions.resource_name_for_dag(root_dag_id))
user = g.user
if action == permissions.ACTION_CAN_READ:
return any(self.get_readable_dag_ids(user))
return any(self.get_editable_dag_ids(user))
def get_all_permissions(self) -> set[tuple[str, str]]:
"""Return all permissions as a set of tuples with the action and resource names."""
return set(
self.appbuilder.get_session.execute(
select(self.action_model.name, self.resource_model.name)
.join(self.permission_model.action)
.join(self.permission_model.resource)
)
)
def create_dag_specific_permissions(self) -> None:
"""
Add permissions to all DAGs.
Creates 'can_read', 'can_edit', and 'can_delete' permissions for all
DAGs, along with any `access_control` permissions provided in them.
This does iterate through ALL the DAGs, which can be slow. See `sync_perm_for_dag`
if you only need to sync a single DAG.
"""
perms = self.get_all_permissions()
dagbag = DagBag(read_dags_from_db=True)
dagbag.collect_dags_from_db()
dags = dagbag.dags.values()
for dag in dags:
root_dag_id = dag.parent_dag.dag_id if dag.parent_dag else dag.dag_id
dag_resource_name = permissions.resource_name_for_dag(root_dag_id)
for action_name in self.DAG_ACTIONS:
if (action_name, dag_resource_name) not in perms:
self._merge_perm(action_name, dag_resource_name)
if dag.access_control is not None:
self.sync_perm_for_dag(dag_resource_name, dag.access_control)
def prefixed_dag_id(self, dag_id: str) -> str:
"""Return the permission name for a DAG id."""
warnings.warn(
"`prefixed_dag_id` has been deprecated. "
"Please use `airflow.security.permissions.resource_name_for_dag` instead.",