Example #1
0
def test_json_roundtrip_of_a_policy_with_context():
    p = Policy('123',
               context={
                   'ip': CIDR('192.168.1.0/24'),
                   'sub': Equal('test-me')
               })
    s = p.to_json()
    p1 = Policy.from_json(s)
    assert '123' == 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('test-me')

    # 'context' wins over deprecated rules
    p = Policy('456',
               context={
                   'ip': CIDR('192.168.1.0/24'),
                   'sub': Equal('foo-bar')
               },
               rules={
                   'ip': CIDR('127.0.0.1'),
                   'sub': Equal('baz')
               })
    s = p.to_json()
    p1 = Policy.from_json(s)
    assert '456' == 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('foo-bar')
    assert p1.context['ip'].satisfied('192.168.1.0')
    assert not hasattr(p1, 'rules')

    # 'rules' are allowed, but they become a 'context' class field
    with pytest.deprecated_call():
        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')
Example #2
0
 def test_returned_condition(self, st):
     uid = str(uuid.uuid4())
     p = Policy(
         uid=uid,
         context={
             'secret': Equal('i-am-a-teacher'),
             'secret2': Equal('i-am-a-husband'),
         },
     )
     st.add(p)
     context = st.get(uid).context
     assert context['secret'].satisfied('i-am-a-teacher')
     assert context['secret2'].satisfied('i-am-a-husband')
Example #3
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
Example #4
0
 def test_to_policy(self):
     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'),
         },
     )
     p_model = PolicyModel.from_policy(p)
     _p = p_model.to_policy()
     assert p.uid == _p.uid
     assert p.type == _p.type
     assert p.description == _p.description
     assert len(p.subjects) == len(_p.subjects)
     assert all(p.subjects[x] == _p.subjects[x]
                for x in range(len(p.subjects)))
     assert len(p.resources) == len(_p.resources)
     assert all(p.resources[x] == _p.resources[x]
                for x in range(len(p.resources)))
     assert len(p.actions) == len(_p.actions)
     assert all(p.actions[x] == _p.actions[x]
                for x in range(len(p.actions)))
     assert 'secret' in _p.context
     assert isinstance(_p.context['secret'], Equal)
     assert _p.context['secret'].val == 'i-am-a-teacher'
Example #5
0
def test_string_equal_satisfied(arg, against, result):
    c = Equal(arg)
    assert result == c.satisfied(against)
    # test after (de)serialization
    assert result == Equal.from_json(Equal(arg).to_json()).satisfied(against)
    # test deprecated class
    with pytest.deprecated_call():
        c = StringEqualRule(arg)
        assert result == c.satisfied(against)
Example #6
0
 def test_from_policy(self):
     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'),
         },
     )
     p_model = PolicyModel.from_policy(p)
     policy__model_assert(p_model, p)
Example #7
0
 def test_find_for_inquiry_with_rules_checker(self, st):
     assertions = unittest.TestCase('__init__')
     st.add(Policy(1, subjects=[{'name': Equal('Max')}], actions=[{'foo': Equal('bar')}]))
     st.add(Policy(2, subjects=[{'name': Equal('Max')}], actions=[{'foo': Equal('bar2')}]))
     st.add(Policy(3, subjects=['sam', 'nina']))
     st.add(Policy(4, actions=[r'<\d+>'], effect=ALLOW_ACCESS, resources=[r'<\w{1,3}>'], subjects=[r'<\w{2}-\d+>']))
     st.add(Policy(5, subjects=[{'name': Equal('Jim')}], actions=[{'foo': Equal('bar3')}]))
     inquiry = Inquiry(subject={'name': 'max'}, action='get', resource='books')
     found = st.find_for_inquiry(inquiry, RulesChecker())
     found = list(found)
     assert 3 == len(found)
     found_uids = list(map(operator.attrgetter('uid'), found))
     found_uids.sort()
     assertions.assertListEqual(['1', '2', '5'], found_uids)
Example #8
0
 def test_get_all_check_policy_properties(self, st):
     p = Policy(
         uid='1',
         description='foo bar баз',
         subjects=('Edward Rooney', 'Florence Sparrow'),
         actions=['<.*>'],
         resources=['<.*>'],
         context={
             'secret': Equal('i-am-a-teacher'),
         },
     )
     st.add(p)
     policies = list(st.get_all(100, 0))
     assert 1 == len(policies)
     assert '1' == policies[0].uid
     assert 'foo bar баз' == policies[0].description
     assert ['Edward Rooney', 'Florence Sparrow'] == policies[0].subjects
     assert ['<.*>'] == policies[0].actions
     assert ['<.*>'] == policies[0].resources
     assert isinstance(policies[0].context['secret'], Equal)
Example #9
0
def test_string_equal_constructor_fails():
    with pytest.raises(TypeError) as excinfo:
        Equal(dict())
    assert 'Initial property should be a string' in str(excinfo.value)
Example #10
0
def test_string_equal_insensitive_satisfied(arg, against, result):
    c = Equal(arg, ci=True)
    assert result == c.satisfied(against)
    # test after (de)serialization
    assert result == Equal.from_json(c.to_json()).satisfied(against)
Example #11
0
def test_exception_raised_when_context_is_not_dict():
    with pytest.raises(PolicyCreationError):
        Policy('1', context=[Equal('foo')])
Example #12
0
    rules = [
        '{"a": 1, "b": 1, "py/object": "test_rule_base.ABRule"}',
        '{"a": "x", "b": "y", "py/object": "test_rule_base.ABRule"}',
    ]
    c1 = Rule.from_json(rules[0])
    c2 = Rule.from_json(rules[1])
    assert isinstance(c1, ABRule)
    assert isinstance(c2, ABRule)
    assert c1.satisfied()
    assert not c2.satisfied()


@pytest.mark.parametrize('rule, satisfied', [
    (ABRule(1, 1), True),
    (ABRule(1, 1.2), False),
    (Equal('foo'), False),
    (vakt.rules.net.CIDR('192.168.0.1/24'), False),
])
def test_json_roundtrip(rule, satisfied):
    c1 = Rule.from_json(rule.to_json())
    assert isinstance(c1, rule.__class__)
    assert c1.__dict__ == rule.__dict__
    assert satisfied == c1.satisfied(None, None)


@pytest.mark.parametrize('data, msg', [
    ("{\"}", "Unterminated string starting"),
])
def test_from_json_fails(data, msg):
    with pytest.raises(RuleCreationError) as excinfo:
        Rule.from_json(data)