示例#1
0
    def parse(cls, json: JSON) -> 'Permission':
        if not isinstance(json.get('scopes', []), list):
            raise ValueError('scopes must be a list')

        return Permission(
            match=json.get('match', None),
            scopes=[Scope(s) for s in json.get('scopes', list())])
示例#2
0
def update_perm(perm_id):
    if not request.json:
        raise ApiError('nothing to change', 400)

    for s in request.json.get('scopes', []):
        if s not in Scope.find_all():
            raise ApiError("'{}' is not a valid Scope".format(s), 400)

    perm = Permission.find_by_id(perm_id)

    if not perm:
        raise ApiError('not found', 404)

    admin_audit_trail.send(current_app._get_current_object(),
                           event='permission-updated',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=perm.id,
                           type='permission',
                           request=request)

    updated = perm.update(**request.json)
    if updated:
        return jsonify(status='ok', permission=updated.serialize)
    else:
        raise ApiError('failed to update permission', 500)
示例#3
0
    def test_custom_scopes(self):

        headers = {
            'Authorization': f"Key {self.api_keys_scopes['admin']}",
            'Content-type': 'application/json'
        }

        # list scopes
        response = self.client.get('/scopes',
                                   content_type='application/json',
                                   headers=headers)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.data.decode('utf-8'))

        self.assertIn('admin:foo', data['scopes'])
        self.assertIn('write:foo.bar', data['scopes'])
        self.assertIn('read:foo.baz', data['scopes'])
        self.assertIn('delete:foo.quux', data['scopes'])

        scope = Scope.from_str(action='write',
                               resource='resource',
                               type='type')
        self.assertEqual(scope.action, 'write')
        self.assertEqual(scope.resource, 'resource')
        self.assertEqual(scope.type, 'type')
示例#4
0
文件: key.py 项目: yrsdi/alerta
 def init_app(self, app: Flask) -> None:
     self.secret_key = app.config['SECRET_KEY']
     self.admin_users = app.config['ADMIN_USERS']
     self.user_default_scopes = [
         Scope(s) for s in app.config['USER_DEFAULT_SCOPES']
     ]
     self.api_key_expire_days = app.config['API_KEY_EXPIRE_DAYS']
示例#5
0
def key(username, want_key, scopes, duration, text, customer, all, force):
    """
    Create an admin API key.
    """
    if username and username not in current_app.config['ADMIN_USERS']:
        raise click.UsageError('User {} not an admin'.format(username))

    if all and want_key:
        raise click.UsageError('Can only set API key with "--username".')

    scopes = [Scope(s) for s in scopes] or [Scope.admin, Scope.write, Scope.read]
    expires = datetime.utcnow() + timedelta(seconds=duration) if duration else None
    text = text or 'Created by alertad script'

    def create_key(admin, key=None):
        key = ApiKey(
            user=admin,
            key=key,
            scopes=scopes,
            expire_time=expires,
            text=text,
            customer=customer
        )
        try:
            key = key.create()
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            return key

    if all:
        for admin in current_app.config['ADMIN_USERS']:
            keys = [k for k in ApiKey.find_by_user(admin) if k.scopes == scopes]
            if keys and not force:
                key = keys[0]
            else:
                key = create_key(admin)
            click.echo('{:40} {}'.format(key.key, key.user))

    elif username:
        keys = [k for k in ApiKey.find_by_user(username) if k.scopes == scopes]
        if want_key:
            found_key = [k for k in keys if k.key == want_key]
            if found_key:
                key = found_key[0]
            else:
                key = create_key(username, key=want_key)
        else:
            if keys and not force:
                key = keys[0]
            else:
                key = create_key(username)
        if key:
            click.echo(key.key)
        else:
            sys.exit(1)

    else:
        raise click.UsageError("Must set '--username' or use '--all'")
示例#6
0
def create_app(config_override: Dict[str, Any] = None, environment: str = None) -> Flask:

    app = Flask(__name__)
    app.config['ENVIRONMENT'] = environment
    config.init_app(app)
    app.config.update(config_override or {})

    tracing.setup_tracing(app)
    logger.setup_logging(app)

    if app.config['USE_PROXYFIX']:
        app.wsgi_app = ProxyFix(app.wsgi_app)  # type: ignore

    hooks.init_app(app)
    audit.init_app(app)
    alarm_model.init_app(app)
    Scope.init_app(app)

    cors.init_app(app)
    compress.init_app(app)
    handlers.register(app)
    key_helper.init_app(app)

    db.init_db(app)
    qb.init_app(app)

    mailer.register(app)
    plugins.register(app)
    custom_webhooks.register(app)

    from alerta.utils.format import CustomJSONEncoder
    app.json_encoder = CustomJSONEncoder

    from alerta.views import api
    app.register_blueprint(api)

    from alerta.webhooks import webhooks
    app.register_blueprint(webhooks)

    from alerta.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from alerta.management import mgmt
    app.register_blueprint(mgmt)

    return app
示例#7
0
文件: key.py 项目: raddessi/alerta
 def from_record(cls, rec) -> 'ApiKey':
     return ApiKey(
         id=rec.id,
         key=rec.key,
         user=rec.user,
         scopes=[Scope(s) for s in rec.scopes],  # legacy type => scopes conversion only required for mongo documents
         text=rec.text,
         expire_time=rec.expire_time,
         count=rec.count,
         last_used_time=rec.last_used_time,
         customer=rec.customer
     )
示例#8
0
 def from_document(cls, doc: Dict[str, Any]) -> 'ApiKey':
     return ApiKey(id=doc.get('id', None) or doc.get('_id'),
                   key=doc.get('key', None) or doc.get('_id'),
                   user=doc.get('user', None),
                   scopes=[Scope(s) for s in doc.get('scopes', list())]
                   or key_helper.type_to_scopes(doc.get(
                       'user', None), doc.get('type', None)) or list(),
                   text=doc.get('text', None),
                   expire_time=doc.get('expireTime', None),
                   count=doc.get('count', None),
                   last_used_time=doc.get('lastUsedTime', None),
                   customer=doc.get('customer', None))
示例#9
0
文件: key.py 项目: yrsdi/alerta
    def parse(cls, json: JSON) -> 'ApiKey':
        if not isinstance(json.get('scopes', []), list):
            raise ValueError('scopes must be a list')

        api_key = ApiKey(
            user=json.get('user', None),
            scopes=[Scope(s) for s in json.get('scopes', [])],
            text=json.get('text', None),
            expire_time=DateTime.parse(json['expireTime']) if 'expireTime' in json else None,
            customer=json.get('customer', None)
        )
        if 'type' in json:
            api_key.scopes = key_helper.type_to_scopes(api_key.user, json['type'])

        return api_key
示例#10
0
 def lookup(cls, login: str, roles: List[str]) -> List[Scope]:
     return [Scope(s) for s in db.get_scopes_by_match(login, matches=roles)]
示例#11
0
 def from_record(cls, rec) -> 'Permission':
     return Permission(id=rec.id,
                       match=rec.match,
                       scopes=[Scope(s) for s in rec.scopes])
示例#12
0
 def from_document(cls, doc: Dict[str, Any]) -> 'Permission':
     return Permission(id=doc.get('id', None) or doc.get('_id'),
                       match=doc.get('match', None),
                       scopes=[Scope(s) for s in doc.get('scopes', list())])
示例#13
0
def list_scopes():
    scopes = Scope.find_all()

    return jsonify(status='ok', scopes=scopes, total=len(scopes))