cornflow 1.1.2__py3-none-any.whl → 1.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cornflow/app.py +8 -0
- cornflow/config.py +43 -5
- cornflow/endpoints/login.py +86 -35
- cornflow/schemas/user.py +18 -2
- cornflow/shared/authentication/auth.py +10 -4
- cornflow/shared/exceptions.py +9 -8
- cornflow/tests/custom_test_case.py +342 -0
- cornflow/tests/unit/test_actions.py +46 -1
- cornflow/tests/unit/test_alarms.py +57 -9
- cornflow/tests/unit/test_apiview.py +45 -1
- cornflow/tests/unit/test_application.py +60 -0
- cornflow/tests/unit/test_cases.py +483 -5
- cornflow/tests/unit/test_cli.py +233 -0
- cornflow/tests/unit/test_commands.py +230 -2
- cornflow/tests/unit/test_dags.py +139 -11
- cornflow/tests/unit/test_data_checks.py +134 -2
- cornflow/tests/unit/test_log_in.py +481 -3
- {cornflow-1.1.2.dist-info → cornflow-1.1.5.dist-info}/METADATA +23 -19
- {cornflow-1.1.2.dist-info → cornflow-1.1.5.dist-info}/RECORD +22 -21
- {cornflow-1.1.2.dist-info → cornflow-1.1.5.dist-info}/WHEEL +1 -1
- {cornflow-1.1.2.dist-info → cornflow-1.1.5.dist-info}/entry_points.txt +0 -1
- {cornflow-1.1.2.dist-info → cornflow-1.1.5.dist-info}/top_level.txt +0 -0
cornflow/app.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
"""
|
2
2
|
Main file with the creation of the app logic
|
3
3
|
"""
|
4
|
+
|
4
5
|
# Full imports
|
5
6
|
import os
|
6
7
|
import click
|
@@ -13,6 +14,8 @@ from flask_cors import CORS
|
|
13
14
|
from flask_migrate import Migrate
|
14
15
|
from flask_restful import Api
|
15
16
|
from logging.config import dictConfig
|
17
|
+
from werkzeug.middleware.dispatcher import DispatcherMiddleware
|
18
|
+
from werkzeug.exceptions import NotFound
|
16
19
|
|
17
20
|
# Module imports
|
18
21
|
from cornflow.commands import (
|
@@ -112,6 +115,11 @@ def create_app(env_name="development", dataconn=None):
|
|
112
115
|
app.cli.add_command(register_deployed_dags)
|
113
116
|
app.cli.add_command(register_dag_permissions)
|
114
117
|
|
118
|
+
if app.config["APPLICATION_ROOT"] != "/" and app.config["EXTERNAL_APP"] == 0:
|
119
|
+
app.wsgi_app = DispatcherMiddleware(
|
120
|
+
NotFound(), {app.config["APPLICATION_ROOT"]: app.wsgi_app}
|
121
|
+
)
|
122
|
+
|
115
123
|
return app
|
116
124
|
|
117
125
|
|
cornflow/config.py
CHANGED
@@ -5,6 +5,12 @@ from apispec.ext.marshmallow import MarshmallowPlugin
|
|
5
5
|
|
6
6
|
|
7
7
|
class DefaultConfig(object):
|
8
|
+
"""
|
9
|
+
Default configuration class
|
10
|
+
"""
|
11
|
+
|
12
|
+
APPLICATION_ROOT = os.getenv("APPLICATION_ROOT", "/")
|
13
|
+
EXTERNAL_APP = int(os.getenv("EXTERNAL_APP", 0))
|
8
14
|
SERVICE_NAME = os.getenv("SERVICE_NAME", "Cornflow")
|
9
15
|
SECRET_TOKEN_KEY = os.getenv("SECRET_KEY")
|
10
16
|
SECRET_BI_KEY = os.getenv("SECRET_BI_KEY")
|
@@ -22,6 +28,11 @@ class DefaultConfig(object):
|
|
22
28
|
SIGNUP_ACTIVATED = int(os.getenv("SIGNUP_ACTIVATED", 1))
|
23
29
|
CORNFLOW_SERVICE_USER = os.getenv("CORNFLOW_SERVICE_USER", "service_user")
|
24
30
|
|
31
|
+
# If service user is allow to log with username and password
|
32
|
+
SERVICE_USER_ALLOW_PASSWORD_LOGIN = int(
|
33
|
+
os.getenv("SERVICE_USER_ALLOW_PASSWORD_LOGIN", 1)
|
34
|
+
)
|
35
|
+
|
25
36
|
# Open deployment (all dags accessible to all users)
|
26
37
|
OPEN_DEPLOYMENT = os.getenv("OPEN_DEPLOYMENT", 1)
|
27
38
|
|
@@ -84,14 +95,17 @@ class DefaultConfig(object):
|
|
84
95
|
|
85
96
|
|
86
97
|
class Development(DefaultConfig):
|
87
|
-
|
88
|
-
|
98
|
+
"""
|
99
|
+
Configuration class for development
|
100
|
+
"""
|
89
101
|
|
90
102
|
ENV = "development"
|
91
103
|
|
92
104
|
|
93
105
|
class Testing(DefaultConfig):
|
94
|
-
"""
|
106
|
+
"""
|
107
|
+
Configuration class for testing
|
108
|
+
"""
|
95
109
|
|
96
110
|
ENV = "testing"
|
97
111
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
@@ -109,8 +123,26 @@ class Testing(DefaultConfig):
|
|
109
123
|
LOG_LEVEL = int(os.getenv("LOG_LEVEL", 10))
|
110
124
|
|
111
125
|
|
126
|
+
class TestingOpenAuth(Testing):
|
127
|
+
"""
|
128
|
+
Configuration class for testing some edge cases with Open Auth login
|
129
|
+
"""
|
130
|
+
|
131
|
+
AUTH_TYPE = 0
|
132
|
+
|
133
|
+
|
134
|
+
class TestingApplicationRoot(Testing):
|
135
|
+
"""
|
136
|
+
Configuration class for testing with application root
|
137
|
+
"""
|
138
|
+
|
139
|
+
APPLICATION_ROOT = "/test"
|
140
|
+
|
141
|
+
|
112
142
|
class Production(DefaultConfig):
|
113
|
-
"""
|
143
|
+
"""
|
144
|
+
Configuration class for production
|
145
|
+
"""
|
114
146
|
|
115
147
|
ENV = "production"
|
116
148
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
@@ -121,4 +153,10 @@ class Production(DefaultConfig):
|
|
121
153
|
PROPAGATE_EXCEPTIONS = True
|
122
154
|
|
123
155
|
|
124
|
-
app_config = {
|
156
|
+
app_config = {
|
157
|
+
"development": Development,
|
158
|
+
"testing": Testing,
|
159
|
+
"production": Production,
|
160
|
+
"testing-oauth": TestingOpenAuth,
|
161
|
+
"testing-root": TestingApplicationRoot,
|
162
|
+
}
|
cornflow/endpoints/login.py
CHANGED
@@ -34,9 +34,11 @@ class LoginBaseEndpoint(BaseMetaResource):
|
|
34
34
|
"""
|
35
35
|
Base endpoint to perform a login action from a user
|
36
36
|
"""
|
37
|
+
|
37
38
|
def __init__(self):
|
38
39
|
super().__init__()
|
39
40
|
self.ldap_class = LDAPBase
|
41
|
+
self.user_role_association = UserRoleModel
|
40
42
|
|
41
43
|
def log_in(self, **kwargs):
|
42
44
|
"""
|
@@ -102,7 +104,9 @@ class LoginBaseEndpoint(BaseMetaResource):
|
|
102
104
|
raise InvalidCredentials()
|
103
105
|
user = self.data_model.get_one_object(username=username)
|
104
106
|
if not user:
|
105
|
-
current_app.logger.info(
|
107
|
+
current_app.logger.info(
|
108
|
+
f"LDAP user {username} does not exist and is created"
|
109
|
+
)
|
106
110
|
email = ldap_obj.get_user_email(username)
|
107
111
|
if not email:
|
108
112
|
email = ""
|
@@ -122,68 +126,115 @@ class LoginBaseEndpoint(BaseMetaResource):
|
|
122
126
|
|
123
127
|
except IntegrityError as e:
|
124
128
|
db.session.rollback()
|
125
|
-
current_app.logger.error(
|
129
|
+
current_app.logger.error(
|
130
|
+
f"Integrity error on user role assignment on log in: {e}"
|
131
|
+
)
|
126
132
|
except DBAPIError as e:
|
127
133
|
db.session.rollback()
|
128
|
-
current_app.logger.error(
|
134
|
+
current_app.logger.error(
|
135
|
+
f"Unknown error on user role assignment on log in: {e}"
|
136
|
+
)
|
129
137
|
|
130
138
|
return user
|
131
139
|
|
132
|
-
def auth_oid_authenticate(
|
140
|
+
def auth_oid_authenticate(
|
141
|
+
self, token: str = None, username: str = None, password: str = None
|
142
|
+
):
|
133
143
|
"""
|
134
|
-
Method in charge of performing the log in with the token issued by an Open ID provider
|
144
|
+
Method in charge of performing the log in with the token issued by an Open ID provider.
|
145
|
+
It has an exception and thus accepts username and password for service users if needed.
|
135
146
|
|
136
147
|
:param str token: the token that the user has obtained from the Open ID provider
|
148
|
+
:param str username: the username of the user to log in
|
149
|
+
:param str password: the password of the user to log in
|
137
150
|
:return: the user object or it raises an error if it has not been possible to log in
|
138
151
|
:rtype: :class:`UserModel`
|
139
152
|
"""
|
140
|
-
oid_provider = int(current_app.config["OID_PROVIDER"])
|
141
153
|
|
142
|
-
|
143
|
-
tenant_id = current_app.config["OID_TENANT_ID"]
|
144
|
-
issuer = current_app.config["OID_ISSUER"]
|
154
|
+
if token:
|
145
155
|
|
146
|
-
|
147
|
-
raise ConfigurationError("The OID provider configuration is not valid")
|
156
|
+
oid_provider = int(current_app.config["OID_PROVIDER"])
|
148
157
|
|
149
|
-
|
150
|
-
|
151
|
-
|
152
|
-
)
|
158
|
+
client_id = current_app.config["OID_CLIENT_ID"]
|
159
|
+
tenant_id = current_app.config["OID_TENANT_ID"]
|
160
|
+
issuer = current_app.config["OID_ISSUER"]
|
153
161
|
|
154
|
-
|
155
|
-
|
156
|
-
elif oid_provider == OID_NONE:
|
157
|
-
raise EndpointNotImplemented("The OID provider configuration is not valid")
|
158
|
-
else:
|
159
|
-
raise EndpointNotImplemented("The OID provider configuration is not valid")
|
162
|
+
if client_id is None or tenant_id is None or issuer is None:
|
163
|
+
raise ConfigurationError("The OID provider configuration is not valid")
|
160
164
|
|
161
|
-
|
165
|
+
if oid_provider == OID_AZURE:
|
166
|
+
decoded_token = self.auth_class().validate_oid_token(
|
167
|
+
token, client_id, tenant_id, issuer, oid_provider
|
168
|
+
)
|
162
169
|
|
163
|
-
|
170
|
+
elif oid_provider == OID_GOOGLE:
|
171
|
+
raise EndpointNotImplemented(
|
172
|
+
"The selected OID provider is not implemented"
|
173
|
+
)
|
174
|
+
elif oid_provider == OID_NONE:
|
175
|
+
raise EndpointNotImplemented(
|
176
|
+
"The OID provider configuration is not valid"
|
177
|
+
)
|
178
|
+
else:
|
179
|
+
raise EndpointNotImplemented(
|
180
|
+
"The OID provider configuration is not valid"
|
181
|
+
)
|
164
182
|
|
165
|
-
|
166
|
-
|
183
|
+
username = decoded_token["preferred_username"]
|
184
|
+
email = decoded_token.get("email", f"{username}@test.org")
|
185
|
+
first_name = decoded_token.get("given_name", "")
|
186
|
+
last_name = decoded_token.get("family_name", "")
|
167
187
|
|
168
|
-
|
188
|
+
user = self.data_model.get_one_object(username=username)
|
169
189
|
|
170
|
-
|
171
|
-
|
190
|
+
if not user:
|
191
|
+
current_app.logger.info(
|
192
|
+
f"OpenID user {username} does not exist and is created"
|
193
|
+
)
|
172
194
|
|
173
|
-
|
195
|
+
data = {
|
196
|
+
"username": username,
|
197
|
+
"email": email,
|
198
|
+
"first_name": first_name,
|
199
|
+
"last_name": last_name,
|
200
|
+
}
|
174
201
|
|
175
|
-
|
176
|
-
|
177
|
-
)
|
202
|
+
user = self.data_model(data=data)
|
203
|
+
user.save()
|
178
204
|
|
179
|
-
|
205
|
+
user_role = self.user_role_association(
|
206
|
+
{
|
207
|
+
"user_id": user.id,
|
208
|
+
"role_id": int(current_app.config["DEFAULT_ROLE"]),
|
209
|
+
}
|
210
|
+
)
|
180
211
|
|
181
|
-
|
212
|
+
user_role.save()
|
213
|
+
|
214
|
+
return user
|
215
|
+
elif (
|
216
|
+
username
|
217
|
+
and password
|
218
|
+
and current_app.config["SERVICE_USER_ALLOW_PASSWORD_LOGIN"] == 1
|
219
|
+
):
|
220
|
+
|
221
|
+
user = self.auth_db_authenticate(username, password)
|
222
|
+
|
223
|
+
if user.is_service_user():
|
224
|
+
return user
|
225
|
+
else:
|
226
|
+
raise InvalidUsage("Invalid request")
|
227
|
+
else:
|
228
|
+
raise InvalidUsage("Invalid request")
|
182
229
|
|
183
230
|
|
184
231
|
def check_last_password_change(user):
|
185
232
|
if user.pwd_last_change:
|
186
|
-
if
|
233
|
+
if (
|
234
|
+
user.pwd_last_change
|
235
|
+
+ timedelta(days=int(current_app.config["PWD_ROTATION_TIME"]))
|
236
|
+
< datetime.utcnow()
|
237
|
+
):
|
187
238
|
return True
|
188
239
|
return False
|
189
240
|
|
cornflow/schemas/user.py
CHANGED
@@ -1,12 +1,14 @@
|
|
1
1
|
"""
|
2
2
|
This file contains the schemas used for the users defined in the application
|
3
3
|
"""
|
4
|
-
|
4
|
+
|
5
|
+
from marshmallow import fields, Schema, validates_schema, ValidationError
|
5
6
|
from .instance import InstanceSchema
|
6
7
|
|
7
8
|
|
8
9
|
class UserSchema(Schema):
|
9
10
|
""" """
|
11
|
+
|
10
12
|
id = fields.Int(dump_only=True)
|
11
13
|
first_name = fields.Str()
|
12
14
|
last_name = fields.Str()
|
@@ -66,9 +68,23 @@ class LoginEndpointRequest(Schema):
|
|
66
68
|
class LoginOpenAuthRequest(Schema):
|
67
69
|
"""
|
68
70
|
This is the schema used by the login endpoint with Open ID protocol
|
71
|
+
Validates that either a token is provided, or both username and password are present
|
69
72
|
"""
|
70
73
|
|
71
|
-
token = fields.Str(required=
|
74
|
+
token = fields.Str(required=False)
|
75
|
+
username = fields.Str(required=False)
|
76
|
+
password = fields.Str(required=False)
|
77
|
+
|
78
|
+
@validates_schema
|
79
|
+
def validate_fields(self, data, **kwargs):
|
80
|
+
if data.get("token") is None:
|
81
|
+
if not data.get("username") or not data.get("password"):
|
82
|
+
raise ValidationError(
|
83
|
+
"A token needs to be provided when using Open ID authentication"
|
84
|
+
)
|
85
|
+
else:
|
86
|
+
if data.get("username") or data.get("password"):
|
87
|
+
raise ValidationError("The login needs to be done with a token only")
|
72
88
|
|
73
89
|
|
74
90
|
class SignupRequest(Schema):
|
@@ -14,6 +14,8 @@ from datetime import datetime, timedelta
|
|
14
14
|
from flask import request, g, current_app, Request
|
15
15
|
from functools import wraps
|
16
16
|
from typing import Union, Tuple
|
17
|
+
|
18
|
+
from jwt import DecodeError
|
17
19
|
from werkzeug.datastructures import Headers
|
18
20
|
|
19
21
|
# Imports from internal modules
|
@@ -103,7 +105,8 @@ class Auth:
|
|
103
105
|
)
|
104
106
|
|
105
107
|
payload = {
|
106
|
-
"exp": datetime.utcnow()
|
108
|
+
"exp": datetime.utcnow()
|
109
|
+
+ timedelta(hours=float(current_app.config["TOKEN_DURATION"])),
|
107
110
|
"iat": datetime.utcnow(),
|
108
111
|
"sub": user_id,
|
109
112
|
}
|
@@ -314,7 +317,10 @@ class Auth:
|
|
314
317
|
:return: the key identifier
|
315
318
|
:rtype: str
|
316
319
|
"""
|
317
|
-
|
320
|
+
try:
|
321
|
+
headers = jwt.get_unverified_header(token)
|
322
|
+
except DecodeError as err:
|
323
|
+
raise InvalidCredentials("Token is not valid")
|
318
324
|
if not headers:
|
319
325
|
raise InvalidCredentials("Token is missing the headers")
|
320
326
|
try:
|
@@ -346,9 +352,9 @@ class Auth:
|
|
346
352
|
try:
|
347
353
|
response = requests.get(discovery_url)
|
348
354
|
response.raise_for_status()
|
349
|
-
except requests.exceptions.HTTPError
|
355
|
+
except requests.exceptions.HTTPError:
|
350
356
|
raise CommunicationError(
|
351
|
-
f"Error getting issuer discovery meta from {discovery_url}"
|
357
|
+
f"Error getting issuer discovery meta from {discovery_url}"
|
352
358
|
)
|
353
359
|
return response.json()
|
354
360
|
|
cornflow/shared/exceptions.py
CHANGED
@@ -2,6 +2,7 @@
|
|
2
2
|
This file contains the different exceptions created to report errors and the handler that registers them
|
3
3
|
on a flask REST API server
|
4
4
|
"""
|
5
|
+
|
5
6
|
from flask import jsonify
|
6
7
|
from webargs.flaskparser import parser
|
7
8
|
from cornflow_client.constants import AirflowError
|
@@ -123,9 +124,11 @@ class ConfigurationError(InvalidUsage):
|
|
123
124
|
|
124
125
|
|
125
126
|
INTERNAL_SERVER_ERROR_MESSAGE = "500 Internal Server Error"
|
126
|
-
INTERNAL_SERVER_ERROR_MESSAGE_DETAIL =
|
127
|
-
|
128
|
-
|
127
|
+
INTERNAL_SERVER_ERROR_MESSAGE_DETAIL = (
|
128
|
+
"The server encountered an internal error and was unable "
|
129
|
+
"to complete your request. Either the server is overloaded or "
|
130
|
+
"there is an error in the application."
|
131
|
+
)
|
129
132
|
|
130
133
|
|
131
134
|
def initialize_errorhandlers(app):
|
@@ -146,6 +149,7 @@ def initialize_errorhandlers(app):
|
|
146
149
|
@app.errorhandler(InvalidData)
|
147
150
|
@app.errorhandler(InvalidPatch)
|
148
151
|
@app.errorhandler(ConfigurationError)
|
152
|
+
@app.errorhandler(CommunicationError)
|
149
153
|
def handle_invalid_usage(error):
|
150
154
|
"""
|
151
155
|
Method to handle the error given by the different exceptions.
|
@@ -187,10 +191,7 @@ def initialize_errorhandlers(app):
|
|
187
191
|
status_code = error.code or status_code
|
188
192
|
error_msg = f"{status_code} {error.name or INTERNAL_SERVER_ERROR_MESSAGE}"
|
189
193
|
error_str = f"{error_msg}. {str(error.description or '') or INTERNAL_SERVER_ERROR_MESSAGE_DETAIL}"
|
190
|
-
response_dict = {
|
191
|
-
"message": error_msg,
|
192
|
-
"error": error_str
|
193
|
-
}
|
194
|
+
response_dict = {"message": error_msg, "error": error_str}
|
194
195
|
response = jsonify(response_dict)
|
195
196
|
|
196
197
|
elif app.config["ENV"] == "production":
|
@@ -202,7 +203,7 @@ def initialize_errorhandlers(app):
|
|
202
203
|
|
203
204
|
response_dict = {
|
204
205
|
"message": INTERNAL_SERVER_ERROR_MESSAGE,
|
205
|
-
"error": INTERNAL_SERVER_ERROR_MESSAGE_DETAIL
|
206
|
+
"error": INTERNAL_SERVER_ERROR_MESSAGE_DETAIL,
|
206
207
|
}
|
207
208
|
response = jsonify(response_dict)
|
208
209
|
else:
|