test_auth.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import pymacaroons
  16. from synapse.handlers.auth import AuthHandler
  17. from tests import unittest
  18. from tests.utils import setup_test_homeserver
  19. from twisted.internet import defer
  20. class AuthHandlers(object):
  21. def __init__(self, hs):
  22. self.auth_handler = AuthHandler(hs)
  23. class AuthTestCase(unittest.TestCase):
  24. @defer.inlineCallbacks
  25. def setUp(self):
  26. self.hs = yield setup_test_homeserver(handlers=None)
  27. self.hs.handlers = AuthHandlers(self.hs)
  28. def test_token_is_a_macaroon(self):
  29. self.hs.config.macaroon_secret_key = "this key is a huge secret"
  30. token = self.hs.handlers.auth_handler.generate_access_token("some_user")
  31. # Check that we can parse the thing with pymacaroons
  32. macaroon = pymacaroons.Macaroon.deserialize(token)
  33. # The most basic of sanity checks
  34. if "some_user" not in macaroon.inspect():
  35. self.fail("some_user was not in %s" % macaroon.inspect())
  36. def test_macaroon_caveats(self):
  37. self.hs.config.macaroon_secret_key = "this key is a massive secret"
  38. self.hs.clock.now = 5000
  39. token = self.hs.handlers.auth_handler.generate_access_token("a_user")
  40. macaroon = pymacaroons.Macaroon.deserialize(token)
  41. def verify_gen(caveat):
  42. return caveat == "gen = 1"
  43. def verify_user(caveat):
  44. return caveat == "user_id = a_user"
  45. def verify_type(caveat):
  46. return caveat == "type = access"
  47. def verify_expiry(caveat):
  48. return caveat == "time < 8600000"
  49. v = pymacaroons.Verifier()
  50. v.satisfy_general(verify_gen)
  51. v.satisfy_general(verify_user)
  52. v.satisfy_general(verify_type)
  53. v.satisfy_general(verify_expiry)
  54. v.verify(macaroon, self.hs.config.macaroon_secret_key)