<commit_before>"""
This test file tests the lib.auth_cache.py

The lib.auth_cache.py only depends on the database model.
"""
from .base import MyTestCase

from privacyidea.lib.authcache import (add_to_cache, delete_from_cache,
                                       update_cache_last_auth, verify_in_cache,
                                       _hash_password,
                                       cleanup)
from passlib.hash import argon2
from privacyidea.models import AuthCache
import datetime


class AuthCacheTestCase(MyTestCase):
    """
    Test the policies on a database level
    """
    password = u"<PASSWORD>"
    username = "hans"
    realm = "realm"
    resolver = "resolver"

    def test_01_write_update_delete_cache(self):
        teststart = datetime.datetime.utcnow()

        r = add_to_cache(self.username, self.realm, self.resolver, self.password)

        self.assertTrue(r > 0)

        auth = AuthCache.query.filter(AuthCache.id == r).first()
        self.assertEqual(auth.username, self.username)
        self.assertTrue(argon2.verify(self.password, auth.authentication))

        self.assertTrue(auth.first_auth > teststart)
        self.assertEqual(auth.last_auth, auth.first_auth)

        update_cache_last_auth(r)
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        self.assertTrue(auth.last_auth > teststart)

        r_delete = delete_from_cache(self.username, self.realm, self.resolver,
                                     self.password)
        self.assertEqual(r, r_delete)

        auth = AuthCache.query.filter(AuthCache.username ==
                                      self.username).first()
        self.assertEqual(auth, None)

    def test_02_verify_cache(self):
        # Verify if no entry in cache
        r = verify_in_cache(self.username, self.realm, self.resolver,
                            self.password)
        self.assertFalse(r)

        # Add Entry to cache
        r = add_to_cache(self.username, self.realm, self.resolver, self.password)
        update_cache_last_auth(r)
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        last_auth1 = auth.last_auth

        first_auth = datetime.datetime.utcnow() - datetime.timedelta(hours=4)
        last_auth = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)

        r = verify_in_cache(self.username, self.realm, self.resolver,
                            self.password, first_auth=first_auth,
                            last_auth=last_auth)
        self.assertTrue(r)

        # The last_auth was increased!
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        last_auth2 = auth.last_auth
        self.assertTrue(last_auth2 > last_auth1)

    def test_03_delete_old_entries(self):
        # Create a VERY old authcache entry
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(<PASSWORD>),
                  first_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=10),
                  last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=2)).save()

        r = verify_in_cache(
            "grandpa", self.realm, self.resolver,
            self.password,
            first_auth=datetime.datetime.utcnow() - datetime.timedelta(hours=4),
            last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                minutes=5))
        # Verification for grandpa fails.
        self.assertFalse(r)
        # The verify_in_cache should have deleted old grandpa entries:
        r = AuthCache.query.filter(AuthCache.username == "grandpa").first()
        self.assertEqual(r, None)

    def test_04_cleanup_authcache(self):
        # cleanup everything!
        r = cleanup(100000000)
        # Create some entries:
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(<PASSWORD>),
                  first_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=10),
                  last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=2)).save()
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(self.password),<commit_msg>Added test to verify counter was increased<commit_after>"""
This test file tests the lib.auth_cache.py

The lib.auth_cache.py only depends on the database model.
"""
from .base import MyTestCase

from privacyidea.lib.authcache import (add_to_cache, delete_from_cache,
                                       update_cache_last_auth, verify_in_cache,
                                       _hash_password,
                                       cleanup)
from passlib.hash import argon2
from privacyidea.models import AuthCache
import datetime


class AuthCacheTestCase(MyTestCase):
    """
    Test the policies on a database level
    """
    password = u"<PASSWORD>"
    username = "hans"
    realm = "realm"
    resolver = "resolver"

    def test_01_write_update_delete_cache(self):
        teststart = datetime.datetime.utcnow()

        r = add_to_cache(self.username, self.realm, self.resolver, self.password)

        self.assertTrue(r > 0)

        auth = AuthCache.query.filter(AuthCache.id == r).first()
        self.assertEqual(auth.username, self.username)
        self.assertTrue(argon2.verify(self.password, auth.authentication))

        self.assertTrue(auth.first_auth > teststart)
        self.assertEqual(auth.last_auth, auth.first_auth)

        update_cache_last_auth(r)
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        self.assertTrue(auth.last_auth > teststart)

        r_delete = delete_from_cache(self.username, self.realm, self.resolver,
                                     self.password)
        self.assertEqual(r, r_delete)

        auth = AuthCache.query.filter(AuthCache.username ==
                                      self.username).first()
        self.assertEqual(auth, None)

    def test_02_verify_cache(self):
        # Verify if no entry in cache
        r = verify_in_cache(self.username, self.realm, self.resolver,
                            self.password)
        self.assertFalse(r)

        # Add Entry to cache
        r = add_to_cache(self.username, self.realm, self.resolver, self.password)
        update_cache_last_auth(r)
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        last_auth1 = auth.last_auth
        auth_count1 = auth.auth_count

        first_auth = datetime.datetime.utcnow() - datetime.timedelta(hours=4)
        last_auth = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)

        r = verify_in_cache(self.username, self.realm, self.resolver,
                            self.password, first_auth=first_auth,
                            last_auth=last_auth)
        self.assertTrue(r)
        self.assertEqual(0, auth_count1)

        # The last_auth was increased!
        auth = AuthCache.query.filter(AuthCache.id == r).first()
        last_auth2 = auth.last_auth
        auth_count2 = auth.auth_count
        self.assertTrue(last_auth2 > last_auth1)
        self.assertEqual(1, auth_count2)

    def test_03_delete_old_entries(self):
        # Create a VERY old authcache entry
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(self.password),
                  first_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=10),
                  last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=2)).save()

        r = verify_in_cache(
            "grandpa", self.realm, self.resolver,
            self.password,
            first_auth=datetime.datetime.utcnow() - datetime.timedelta(hours=4),
            last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                minutes=5))
        # Verification for grandpa fails.
        self.assertFalse(r)
        # The verify_in_cache should have deleted old grandpa entries:
        r = AuthCache.query.filter(AuthCache.username == "grandpa").first()
        self.assertEqual(r, None)

    def test_04_cleanup_authcache(self):
        # cleanup everything!
        r = cleanup(100000000)
        # Create some entries:
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(self.password),
                  first_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=10),
                  last_auth=datetime.datetime.utcnow() - datetime.timedelta(
                      days=2)).save()
        AuthCache("grandpa", self.realm, self.resolver, _hash_password(self.password),
{'fraction_non_alphanumeric': 0.09768038232894277, 'fraction_numerical': 0.008625713952675137, 'mean_word_length': 2.205080313784087, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5973692', 'n_tokens_mistral': 2517, 'n_tokens_neox': 2432, 'n_words': 451}