<reponame>google/article-recommender
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from recommender import xsrf

import time
import datetime
import unittest


class XsrfTest(unittest.TestCase):

  def testToken(self):
    token = xsrf.GenerateToken('secret1', 'user1', 'action1')
    self.assertTrue(xsrf.ValidateToken('secret1', token, 'user1', 'action1'))

    # Changing any part will make the token invalid.
    self.assertFalse(xsrf.ValidateToken('secret2', token, 'user1', 'action1'))
    self.assertFalse(xsrf.ValidateToken('secret1', token, 'user2', 'action1'))
    self.assertFalse(xsrf.ValidateToken('secret1', token, 'user1', 'action2'))

    # The token becomes invalid after some time.
    self.assertFalse(
        xsrf.ValidateToken(
            'secret1',
            token,
            'user1',
            'action1',
            now_timestamp=time.time() + xsrf._TOKEN_TTL_SECONDS))

    # If 'now' is long before the expiry (one day) then the token is also
    # invalid.
    one_day_ago = time.time() - datetime.timedelta(days=1).total_seconds()
    self.assertFalse(
        xsrf.ValidateToken(
            'secret1', token, 'user1', 'action1', now_timestamp=one_day_ago))

    # The token is not generated by GenerateToken.
    self.assertFalse(
        xsrf.ValidateToken('secret1', 'fake_token', 'user1', 'action1'))

    self.assertFalse(
        xsrf.ValidateToken('secret1', token + ':1230', 'user1', 'action1'))

    self.assertFalse(
        xsrf.ValidateToken('secret1', 'abc:1230', 'user1', 'action1'))
