Ejemplo n.º 1
0
 def test_login(id):
     print("test: logging user with id", id)
     response = make_response()
     user = User.query.get(id)
     login_user(user)
     set_identity(user)
     return response
Ejemplo n.º 2
0
def test_aclserializer(app, db, es, es_acl_prepare, test_users):
    with db.session.begin_nested():
        acl1 = DefaultACL(name='default',
                          schemas=[RECORD_SCHEMA],
                          priority=0,
                          originator=test_users.u1,
                          operation='get')
        actor1 = UserActor(name='auth',
                           users=[test_users.u1],
                           acl=acl1,
                           originator=test_users.u1)

        db.session.add(acl1)
        db.session.add(actor1)

    pid, rec = create_record({'title': 'blah'}, clz=SchemaEnforcingRecord)
    RecordIndexer().index(rec)
    current_search_client.indices.flush()

    assert current_jsonschemas.url_to_path(
        rec['$schema']) in current_explicit_acls.enabled_schemas
    assert list(DefaultACL.get_record_acls(rec)) != []

    index, doc_type = schema_to_index(RECORD_SCHEMA)
    data = current_search_client.get(index=index,
                                     doc_type=doc_type,
                                     id=str(pid.object_uuid))['_source']
    assert '_invenio_explicit_acls' in data
    assert len(data['_invenio_explicit_acls']) == 1

    with app.test_request_context():
        login_user(test_users.u1)
        set_identity(test_users.u1)

        acljson_serializer = ACLJSONSerializer(RecordSchemaV1,
                                               acl_rest_endpoint='recid',
                                               replace_refs=True)
        serialized = json.loads(acljson_serializer.serialize(pid, rec))
        assert serialized['invenio_explicit_acls'] == ["get"]

    with app.test_client() as client:
        login(client, test_users.u1)
        search_results = client.get(url_for('invenio_records_rest.recid_list'))
        search_results = get_json(search_results)
        hits = search_results['hits']['hits']
        assert len(hits) == 1
        assert hits[0]['invenio_explicit_acls'] == ["get"]
Ejemplo n.º 3
0
def test_get_elasticsearch_query(app, db, es, test_users):
    with current_app.test_request_context():
        assert Term(_invenio_explicit_acls__system_role='any_user'
                    ) == SystemRoleActor.get_elasticsearch_query(
                        AnonymousUser(), {})

        set_identity(test_users.u1)
        assert Terms(_invenio_explicit_acls__system_role=['any_user',
                                                          'authenticated_user']) == \
               SystemRoleActor.get_elasticsearch_query(test_users.u1, {})

        # faked user - different identity in flask.g than user
        with pytest.raises(
                AttributeError,
                message='user whose id does not match Identity in flask.g'):
            SystemRoleActor.get_elasticsearch_query(test_users.u2, {})

        set_identity(test_users.u2)
        assert Terms(_invenio_explicit_acls__system_role=['any_user', 'authenticated_user']) == \
               SystemRoleActor.get_elasticsearch_query(test_users.u2, {})
Ejemplo n.º 4
0
def test_user_matches(app, db, es, test_users):
    with db.session.begin_nested():
        actor = SystemRoleActor(name='test',
                                originator=test_users.u1,
                                system_role='authenticated_user')
        db.session.add(actor)

    with current_app.test_request_context():
        assert not actor.user_matches(AnonymousUser(),
                                      {'system_roles': [any_user]})

        set_identity(test_users.u1)
        assert actor.user_matches(test_users.u1, {})

        # faked user - different identity in flask.g than user
        set_identity(test_users.u1)
        with pytest.raises(AttributeError):
            actor.user_matches(test_users.u2, {})

        set_identity(test_users.u2)
        assert actor.user_matches(test_users.u2, {})

        set_identity(test_users.u3)
        assert actor.user_matches(test_users.u3, {})
Ejemplo n.º 5
0
def test_aclrecordsearch_returnall(app, db, es, es_acl_prepare, test_users):
    with db.session.begin_nested():
        acl1 = ElasticsearchACL(name='test', schemas=[RECORD_SCHEMA],
                                priority=0, operation='get', originator=test_users.u1,
                                record_selector={'term': {
                                    'keywords': 'test'
                                }})
        actor1 = SystemRoleActor(name='auth', system_role='any_user', acl=acl1, originator=test_users.u1)
        db.session.add(acl1)
        db.session.add(actor1)

    current_explicit_acls.reindex_acl(acl1, delayed=False)

    with app.test_client() as client:
        login(client, test_users.u1)
        response = client.post(records_url(),
                               data=json.dumps({'title': 'blah', 'contributors': [], 'keywords': ['blah']}),
                               content_type='application/json')
        assert response.status_code == 201
        rest_metadata = get_json(response)['metadata']
        assert 'control_number' in rest_metadata

    # make sure indices are flushed
    current_search_client.indices.refresh()
    current_search_client.indices.flush()

    index, doc_type = schema_to_index(RECORD_SCHEMA)

    record_uuid = PersistentIdentifier.get('recid', rest_metadata['control_number']).object_uuid
    with app.test_request_context():
        login_user(test_users.u1)
        set_identity(test_users.u1)
        assert current_user == test_users.u1

        # acl1 does not apply to the resource so the search must return no data
        assert not len(
            ACLRecordsSearch(index=index, doc_type=doc_type, operation='get').get_record(record_uuid).execute())

        # when acl_return_all is specified, return all matching records regardless of ACL
        with_all = ACLRecordsSearch(index=index, doc_type=doc_type).acl_return_all().get_record(
            record_uuid).execute().hits
        assert len(with_all) == 1
        assert with_all[0]['_invenio_explicit_acls'] == []

    # add another acl, this one maps to the record
    with db.session.begin_nested():
        acl2 = ElasticsearchACL(name='test', schemas=[RECORD_SCHEMA],
                                priority=0, operation='get', originator=test_users.u1,
                                record_selector={'term': {
                                    'keywords': 'blah'
                                }})
        actor2 = UserActor(name='u2', users=[test_users.u2], acl=acl2, originator=test_users.u1)
        db.session.add(acl2)
        db.session.add(actor2)

    current_explicit_acls.reindex_acl(acl2, delayed=False)

    # make sure indices are flushed
    current_search_client.indices.refresh()
    current_search_client.indices.flush()

    # for the same user acl_return_all() must return the record and effective acls
    with app.test_request_context():
        login_user(test_users.u1)
        set_identity(test_users.u1)

        # when acl_return_all is specified, return all matching records regardless of ACL
        with_all = ACLRecordsSearch(index=index, doc_type=doc_type).acl_return_all().get_record(
            record_uuid).execute().hits
        assert len(with_all) == 1
        assert clear_timestamp(with_all[0].to_dict()['_invenio_explicit_acls']) == [
            {
                'operation': 'get',
                'id': acl2.id,
                'timestamp': 'cleared',
                'user': [2]
            }
        ]

    # for user2 plain ACLRecordsSearch must return the record and effective acls
    with app.test_request_context():
        login_user(test_users.u2)
        set_identity(test_users.u2)
        # when acl_return_all is specified, return all matching records regardless of ACL
        with_all = ACLRecordsSearch(index=index, doc_type=doc_type).get_record(record_uuid).execute().hits
        assert len(with_all) == 1
        assert clear_timestamp(with_all[0].to_dict()['_invenio_explicit_acls']) == [
            {
                'operation': 'get',
                'id': acl2.id,
                'timestamp': 'cleared',
                'user': [2]
            }
        ]