示例#1
0
 def test_add(self, st):
     id = str(uuid.uuid4())
     p = Policy(
         uid=id,
         description='foo bar баз',
         subjects=('Edward Rooney', 'Florence Sparrow'),
         actions=['好'],
         resources=['<.*>'],
         context={
             'secret': Equal('i-am-a-teacher'),
             'rating': And(Eq(80), Greater(80))
         },
     )
     st.add(p)
     back = st.get(id)
     assert id == back.uid
     assert 'foo bar баз' == back.description
     assert isinstance(back.context['secret'], Equal)
     assert isinstance(back.context['rating'], And)
     assert '好' == back.actions[0]
     st.add(
         Policy('2',
                actions=[Eq('get'), Eq('put')],
                subjects=[Any()],
                resources=[{
                    'books': Eq('Harry')
                }]))
     assert '2' == st.get('2').uid
     assert 2 == len(st.get('2').actions)
     assert 1 == len(st.get('2').subjects)
     assert isinstance(st.get('2').subjects[0], Any)
     assert 1 == len(st.get('2').resources)
     assert isinstance(st.get('2').resources[0]['books'], Eq)
     assert 'Harry' == st.get('2').resources[0]['books'].val
示例#2
0
def test_not_rule_bad_args():
    expected_msg = "Arguments should be of Rule class or it's derivatives"
    with pytest.raises(TypeError) as excinfo:
        Not(123)
    assert expected_msg in str(excinfo.value)
    with pytest.raises(TypeError) as excinfo:
        Not([Greater(-1)])
    assert expected_msg in str(excinfo.value)
示例#3
0
    assert result == Rule.from_json(jsn).satisfied(against)


def test_and_or_rules_bad_args():
    expected_msg = "Arguments should be of Rule class or it's derivatives"
    with pytest.raises(TypeError) as excinfo:
        And(Inquiry())
    assert expected_msg in str(excinfo.value)
    with pytest.raises(TypeError) as excinfo:
        Or(Inquiry(), 123)
    assert expected_msg in str(excinfo.value)


@pytest.mark.parametrize('rules, what, inquiry, result', [
    ([], 1, None, False),
    ([Greater(-1)], 1, None, True),
    ([Greater(55)], 1, None, False),
    ([Greater(-1), Less(10)], 1, None, True),
    ([Greater(-1), Less(10), Eq(700)], 1, None, False),
    ([Eq('read'), In('read', 'write'),
      ActionEqual()], 'read', Inquiry(action='read'), True),
    ([Eq('read'), In('write'), ActionEqual()
      ], 'read', Inquiry(action='read'), False),
])
def test_and_rule(rules, what, inquiry, result):
    r = And(*rules)
    assert result == r.satisfied(what, inquiry)
    # test after (de)serialization
    assert result == Rule.from_json(And(*rules).to_json()).satisfied(
        what, inquiry)
示例#4
0
        assert '789' == p1.uid
        assert 2 == len(p1.context)
        assert 'ip' in p1.context
        assert 'sub' in p1.context
        assert isinstance(p1.context['ip'], CIDR)
        assert isinstance(p1.context['sub'], Equal)
        assert p1.context['sub'].satisfied('baz')
        assert p1.context['ip'].satisfied('127.0.0.1')
        assert not hasattr(p1, 'rules')


@pytest.mark.parametrize('policy', [
    Policy(1,
           subjects=[{
               'name': Eq('Max'),
               'rate': Greater(90)
           }],
           actions=[Eq('get'), Eq('post')],
           resources=[Any()]),
    Policy(2,
           subjects=[{
               'login': Eq('sally')
           }],
           actions=[Eq('get'), Eq('post')],
           context={'ip': Eq('127.0.0.1')}),
    Policy(3,
           subjects=[{
               'rating': AnyIn(1, 2)
           }],
           actions=[And(Eq('get'), Eq('post'))]),
    Policy(4,
示例#5
0
        p = Policy('789', rules={'ip': CIDR('127.0.0.1'), 'sub': Equal('baz')})
        s = p.to_json()
        p1 = Policy.from_json(s)
        assert '789' == p1.uid
        assert 2 == len(p1.context)
        assert 'ip' in p1.context
        assert 'sub' in p1.context
        assert isinstance(p1.context['ip'], CIDR)
        assert isinstance(p1.context['sub'], Equal)
        assert p1.context['sub'].satisfied('baz')
        assert p1.context['ip'].satisfied('127.0.0.1')
        assert not hasattr(p1, 'rules')


@pytest.mark.parametrize('policy', [
    Policy(1, subjects=[{'name': Eq('Max'), 'rate': Greater(90)}], actions=[Eq('get'), Eq('post')], resources=[Any()]),
    Policy(2, subjects=[{'login': Eq('sally')}], actions=[Eq('get'), Eq('post')], context={'ip': Eq('127.0.0.1')}),
    Policy(3, subjects=[{'rating': AnyIn(1, 2)}], actions=[And(Eq('get'), Eq('post'))]),
    Policy(4, subjects=[{'rating': AnyIn(1, 2)}], actions=[And(Eq('get'), Eq('post'))]),
    Policy(5, actions=[Eq('get')]),
])
def test_json_roundtrip_of_a_rules_based_policy(policy):
    pj = policy.to_json()
    p2 = Policy.from_json(pj)
    assert policy.to_json() == p2.to_json()


@pytest.mark.parametrize('data, exception, msg', [
    ('{}', PolicyCreationError, "'uid'"),
    ('{"uid":}', ValueError, ''),
    ('', ValueError, ''),
示例#6
0
     Policy(uid=1,
            effect=ALLOW_ACCESS,
            subjects=[Any()],
            actions=[Any()],
            resources=[Eq('/metrics/cpu'),
                       Eq('/metrics/mem')]),
     Inquiry(subject='Sally', action='GET', resource='/metrics/cpu'),
     RulesChecker(),
     True,
 ),
 (
     'RulesChecker: Should match because of user\'s stars and correct book',
     Policy(uid=1,
            effect=ALLOW_ACCESS,
            subjects=[Eq('Admin'), {
                'stars': Greater(50)
            }],
            actions=[Any()],
            resources=[{
                'book': Eq('Potter')
            }, {
                'magzine': Any()
            }]),
     Inquiry(
         subject={'stars': 870}, action='GET', resource={'book': 'Potter'}),
     RulesChecker(),
     True,
 ),
 (
     'RulesChecker: Should match because of any magazine and Admin user',
     Policy(uid=1,