Пример #1
0
    def check_auth_info(self, auth_info, context):
        logging.debug('auth_info: %s', auth_info)
        project = Project.query.filter_by(
            name=auth_info.project_name).first()
        if project is None:
            raise UnauthorizedException('Invalid project')
        project_config = project.get_config()
        # TODO: fix token verification
        # if project_config.token != auth_info.auth_token:
        #     raise UnauthorizedException('Invalid token')

        # Use first participant to mock for unit test
        # TODO: Fix for multi-peer
        source_party = project_config.participants[0]
        if os.environ.get('FLASK_ENV') == 'production':
            metadata = dict(context.invocation_metadata())
            # ssl-client-subject-dn example:
            # CN=*.fl-xxx.com,OU=security,O=security,L=beijing,ST=beijing,C=CN
            cn = metadata.get('ssl-client-subject-dn').split(',')[0][5:]
            for party in project_config.participants:
                if party.domain_name == cn:
                    source_party = party
            if source_party is None:
                raise UnauthorizedException('Invalid domain')
        return project, source_party
Пример #2
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            required=True,
                            help='username is empty')
        parser.add_argument('password',
                            required=True,
                            help='password is empty')
        data = parser.parse_args()
        username = data['username']
        password = base64decode(data['password'])
        user = User.query.filter_by(username=username).filter_by(
            state=State.ACTIVE).first()
        if user is None:
            raise NotFoundException(f'Failed to find user: {username}')
        if not user.verify_password(password):
            raise UnauthorizedException('Invalid password')
        token = create_access_token(identity=username)
        decoded_token = decode_token(token)

        session = Session(jti=decoded_token.get('jti'),
                          expired_at=datetime.datetime.fromtimestamp(
                              decoded_token.get('exp')))
        db.session.add(session)
        db.session.commit()

        return {
            'data': {
                'user': user.to_dict(),
                'access_token': token
            }
        }, HTTPStatus.OK
Пример #3
0
 def _check_metrics_public(self, request, context):
     project, party = self.check_auth_info(request.auth_info, context)
     job = db.session.query(Job).filter_by(name=request.job_name,
                                           project_id=project.id).first()
     assert job is not None, f'job {request.job_name} not found'
     workflow = job.workflow
     if not workflow.metric_is_public:
         raise UnauthorizedException('Metric is private!')
     return job
Пример #4
0
 def check_auth_info(self, auth_info):
     logging.debug('auth_info: %s', auth_info)
     project = Project.query.filter_by(name=auth_info.project_name).first()
     if project is None:
         raise UnauthorizedException('Invalid project')
     project_config = project.get_config()
     # TODO: fix token verification
     # if project_config.token != auth_info.auth_token:
     #     raise UnauthorizedException('Invalid token')
     if project_config.domain_name != auth_info.target_domain:
         raise UnauthorizedException('Invalid domain')
     source_party = None
     for party in project_config.participants:
         if party.domain_name == auth_info.source_domain:
             source_party = party
     if source_party is None:
         raise UnauthorizedException('Invalid domain')
     return project, source_party
Пример #5
0
 def _check_authorization(arg, extra_allowed: set = None):
     if not arg:
         return
     allowed_fields = Envs.KIBANA_ALLOWED_FIELDS | (extra_allowed or set())
     for query in Kibana.LOGICAL_PATTERN.split(arg):
         if not query:
             continue
         if query.split(':')[0] not in allowed_fields:
             raise UnauthorizedException(
                 'Query [{}] is not authorized.'.format(query))
Пример #6
0
 def get_job_metrics(self, request, context):
     with self._app.app_context():
         project, party = self.check_auth_info(request.auth_info, context)
         job = Job.query.filter_by(name=request.job_name,
                                   project_id=project.id).first()
         assert job is not None, f'Job {request.job_name} not found'
         workflow = job.workflow
         if not workflow.metric_is_public:
             raise UnauthorizedException('Metric is private!')
         metrics = JobMetricsBuilder(job).plot_metrics()
         return service_pb2.GetJobMetricsResponse(
             status=common_pb2.Status(code=common_pb2.STATUS_SUCCESS),
             metrics=json.dumps(metrics))
Пример #7
0
 def get_job_kibana(self, job_name, json_args):
     msg = service_pb2.GetJobKibanaRequest(auth_info=self._auth_info,
                                           job_name=job_name,
                                           json_args=json_args)
     response = self._client.GetJobKibana(request=msg,
                                          metadata=self._get_metadata(),
                                          timeout=Envs.GRPC_CLIENT_TIMEOUT)
     status = response.status
     if status.code != common_pb2.STATUS_SUCCESS:
         if status.code == common_pb2.STATUS_UNAUTHORIZED:
             raise UnauthorizedException(status.msg)
         if status.code == common_pb2.STATUS_INVALID_ARGUMENT:
             raise InvalidArgumentException(status.msg)
         logging.debug('get_job_kibana request error: %s',
                       response.status.msg)
     return response
Пример #8
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            required=True,
                            help='username is empty')
        parser.add_argument('password',
                            required=True,
                            help='password is empty')
        data = parser.parse_args()
        username = data['username']
        password = data['password']

        user = User.query.filter_by(username=username).first()
        if user is None:
            raise NotFoundException()
        if not user.verify_password(password):
            raise UnauthorizedException('Invalid password')
        token = create_access_token(identity=username)
        return {'access_token': token}, HTTPStatus.OK
Пример #9
0
    def put(self, user_id):
        user = self._find_user(user_id)
        data = request.get_json()
        new_password = data.pop('new_password', None)
        if new_password:
            old_password = data.pop('old_password', None)

        if data:
            details = {}
            for key in data.keys():
                details[key] = 'Invalid field'
            raise InvalidArgumentException(details=details)

        if new_password:
            if not user.verify_password(old_password):
                raise UnauthorizedException(message='Wrong old password')
            user.set_password(new_password)

        db.session.commit()
        return {'username': user.username}, HTTPStatus.OK
Пример #10
0
    def patch(self, user_id):
        user = self._find_user(user_id)

        current_user = get_current_user()
        if current_user.role != Role.ADMIN and current_user.id != user_id:
            raise UnauthorizedException('user cannot modify others infomation')

        mutable_attrs = MUTABLE_ATTRS_MAPPER.get(current_user.role)

        data = request.get_json()
        for k, v in data.items():
            if k not in mutable_attrs:
                raise InvalidArgumentException(f'cannot edit {k} attribute!')
            if k == 'password':
                user.set_password(v)
            else:
                setattr(user, k, v)

        db.session.commit()
        return {'data': user.to_dict()}, HTTPStatus.OK
Пример #11
0
    def get_job_metrics(self, request, context):
        with self._app.app_context():
            project, party = self.check_auth_info(request.auth_info, context)
            workflow = Workflow.query.filter_by(
                name=request.workflow_name).first()
            assert workflow is not None, \
                f'Workflow {request.workflow_name} not found'
            if not workflow.metric_is_public:
                raise UnauthorizedException('Metric is private!')

            job = None
            for i in workflow.get_jobs():
                if i.get_config().name == request.job_name:
                    job = i
                    break

            assert job is not None, f'Job {request.job_name} not found'

            metrics = JobMetricsBuilder(job).plot_metrics()

            return service_pb2.GetJobMetricsResponse(
                status=common_pb2.Status(code=common_pb2.STATUS_SUCCESS),
                metrics=json.dumps(metrics))
Пример #12
0
 def wrapper_inside(*args, **kwargs):
     current_user = get_current_user()
     if current_user.role != Role.ADMIN:
         raise UnauthorizedException('only admin can operate this')
     return f(*args, **kwargs)