test_auth.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 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 mock import Mock, NonCallableMock
  17. from synapse.handlers.auth import AuthHandler
  18. from tests import unittest
  19. from tests.utils import setup_test_homeserver
  20. from twisted.internet import defer
  21. class AuthHandlers(object):
  22. def __init__(self, hs):
  23. self.auth_handler = AuthHandler(hs)
  24. class AuthTestCase(unittest.TestCase):
  25. @defer.inlineCallbacks
  26. def setUp(self):
  27. self.hs = yield setup_test_homeserver(handlers=None)
  28. self.hs.handlers = AuthHandlers(self.hs)
  29. def test_token_is_a_macaroon(self):
  30. self.hs.config.macaroon_secret_key = "this key is a huge secret"
  31. token = self.hs.handlers.auth_handler.generate_access_token("some_user")
  32. # Check that we can parse the thing with pymacaroons
  33. macaroon = pymacaroons.Macaroon.deserialize(token)
  34. # The most basic of sanity checks
  35. if "some_user" not in macaroon.inspect():
  36. self.fail("some_user was not in %s" % macaroon.inspect())
  37. def test_macaroon_caveats(self):
  38. self.hs.config.macaroon_secret_key = "this key is a massive secret"
  39. self.hs.clock.now = 5000
  40. token = self.hs.handlers.auth_handler.generate_access_token("a_user")
  41. macaroon = pymacaroons.Macaroon.deserialize(token)
  42. def verify_gen(caveat):
  43. return caveat == "gen = 1"
  44. def verify_user(caveat):
  45. return caveat == "user_id = a_user"
  46. def verify_type(caveat):
  47. return caveat == "type = access"
  48. def verify_expiry(caveat):
  49. return caveat == "time < 8600000"
  50. v = pymacaroons.Verifier()
  51. v.satisfy_general(verify_gen)
  52. v.satisfy_general(verify_user)
  53. v.satisfy_general(verify_type)
  54. v.satisfy_general(verify_expiry)
  55. v.verify(macaroon, self.hs.config.macaroon_secret_key)