#!/usr/bin/python3
# ----------------------------------------------------------------------
#    Copyright (C) 2022 Canonical, Ltd.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
# ----------------------------------------------------------------------

import unittest
from collections import namedtuple

from apparmor.logparser import ReadLog

from common_test import AATest, setup_all_loops

from apparmor.rule.userns import UserNamespaceRule, UserNamespaceRuleset
from apparmor.common import AppArmorException, AppArmorBug, hasher
from apparmor.translations import init_translation
_ = init_translation()


class UserNamespaceTestParse(AATest):
    tests = (
        #                                          access                 audit  deny   allow  comment
        ('userns,',              UserNamespaceRule(UserNamespaceRule.ALL, False, False, False, '')),
        ('userns create,',       UserNamespaceRule(('create'),            False, False, False, '')),
        ('audit userns create,', UserNamespaceRule(('create'),            True,  False, False, '')),
        ('deny userns,',         UserNamespaceRule(UserNamespaceRule.ALL, False, True,  False, '')),
        ('audit allow userns,',  UserNamespaceRule(UserNamespaceRule.ALL, True,  False, True,  '')),
        ('userns create, # cmt', UserNamespaceRule(('create'),            False, False, False, ' # cmt')),
    )

    def _run_test(self, rawrule, expected):
        self.assertTrue(UserNamespaceRule.match(rawrule))
        obj = UserNamespaceRule.create_instance(rawrule)
        expected.raw_rule = rawrule.strip()
        self.assertTrue(obj.is_equal(expected, True))


class UserNamespaceTestParseInvalid(AATest):
    tests = (
        #                                    exception          matches regex
        ('userns invalidaccess,',           (AppArmorException, True)),
        ('priority=a userns,',              (AppArmorException, False)),
        ('priority=1042 userns,',           (AppArmorException, True)),
        ('foo,',                            (AppArmorException, False)),
    )

    def _run_test(self, rawrule, expected):
        self.parseInvalidRule(UserNamespaceRule, rawrule, expected)


class UserNamespaceTestIsEqual(AATest):
    def test_diff_non_usernsrule(self):
        exp = namedtuple('exp', ('audit', 'deny', 'priority'))
        obj = UserNamespaceRule(('create'))
        with self.assertRaises(AppArmorBug):
            obj.is_equal(exp(False, False, None), False)

    def test_diff_access(self):
        obj1 = UserNamespaceRule(UserNamespaceRule.ALL)
        obj2 = UserNamespaceRule(('create'))
        self.assertFalse(obj1.is_equal(obj2, False))


class InvalidUserNamespaceInit(AATest):
    tests = (
        # init params  expected exception
        ((''),         TypeError),          # empty access
        (('    '),     AppArmorBug),        # whitespace access
        (('xyxy'),     AppArmorException),  # invalid access
        (dict(),       TypeError),          # wrong type for access
        (None,         TypeError),          # wrong type for access
    )

    def _run_test(self, params, expected):
        with self.assertRaises(expected):
            UserNamespaceRule(*params)

    def test_missing_params(self):
        with self.assertRaises(TypeError):
            UserNamespaceRule()

    def test_invalid_priority_1(self):
        with self.assertRaises(TypeError):
            UserNamespaceRule(UserNamespaceRule.ALL, priority=UserNamespaceRule.ALL)

    def test_invalid_priority_2(self):
        with self.assertRaises(AppArmorException):
            UserNamespaceRule(UserNamespaceRule.ALL, priority='invalid')


class WriteUserNamespaceTestAATest(AATest):
    tests = (
        #  raw rule                              clean rule
        ('     userns         ,    # foo    ',   'userns, # foo'),
        ('    audit     userns create,',         'audit userns create,'),
        ('   deny userns      ,# foo bar',       'deny userns, # foo bar'),
        ('   allow userns  create   ,# foo bar', 'allow userns create, # foo bar'),
        ('userns,',                              'userns,'),
        ('userns create,',                       'userns create,'),
        (' priority = -1 allow userns  create,', 'priority=-1 allow userns create,'),
        (' priority =  0 allow userns  create,', 'priority=0 allow userns create,'),
        (' priority=+234 allow userns  create,', 'priority=234 allow userns create,'),
        (' priority = 65 allow userns  create,', 'priority=65 allow userns create,'),
    )

    def _run_test(self, rawrule, expected):
        self.assertTrue(UserNamespaceRule.match(rawrule))
        obj = UserNamespaceRule.create_instance(rawrule)
        clean = obj.get_clean()
        raw = obj.get_raw()

        self.assertEqual(expected.strip(), clean, 'unexpected clean rule')
        self.assertEqual(rawrule.strip(), raw, 'unexpected raw rule')

    def test_write_manually(self):
        obj = UserNamespaceRule('create', allow_keyword=True)

        expected = '    allow userns create,'

        self.assertEqual(expected, obj.get_clean(2), 'unexpected clean rule')
        self.assertEqual(expected, obj.get_raw(2), 'unexpected raw rule')

    def test_write_invalid_access(self):
        obj = UserNamespaceRule('create')
        obj.access = ''
        with self.assertRaises(AppArmorBug):
            obj.get_clean()


class UserNamespaceIsCoveredTest(AATest):
    def test_is_covered(self):
        obj = UserNamespaceRule(UserNamespaceRule.ALL)
        self.assertTrue(obj.is_covered(UserNamespaceRule(('create'))))
        self.assertTrue(obj.is_covered(UserNamespaceRule(UserNamespaceRule.ALL)))

    def test_is_not_covered(self):
        obj = UserNamespaceRule(('create'))
        self.assertFalse(obj.is_covered(UserNamespaceRule(UserNamespaceRule.ALL)))


class UserNamespaceLogprofHeaderTest(AATest):
    tests = (
        ('userns,',        [_('Access mode'), _('ALL')]),
        ('userns create,', [_('Access mode'), 'create']),
    )

    def _run_test(self, params, expected):
        obj = UserNamespaceRule.create_instance(params)
        self.assertEqual(obj.logprof_header(), expected)

    def test_unconfined_usens_from_log(self):

        log = 'type=AVC msg=audit(1720613712.153:168): apparmor="AUDIT" operation="userns_create" class="namespace" info="Userns create - transitioning profile" profile="unconfined" pid=5630 comm="unshare" requested="userns_create" target="unprivileged_userns" execpath="/usr/bin/unshare"'
        parser = ReadLog('', '', '')

        hl = hasher()

        ev = parser.parse_event(log)
        UserNamespaceRule.hashlog_from_event(hl, ev)

        expected = {'create': True}
        self.assertEqual(hl, expected)

        ur = UserNamespaceRule.from_hashlog(hl)

        expected = UserNamespaceRule('create')

        self.assertTrue(expected.is_equal(next(ur)))
        with self.assertRaises(StopIteration):
            next(ur)


class UserNamespaceGlobTestAATest(AATest):
    def test_glob(self):
        self.assertEqual(UserNamespaceRuleset().get_glob('userns create,'), 'userns,')


setup_all_loops(__name__)
if __name__ == '__main__':
    unittest.main(verbosity=1)
