test_auth.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from twisted.trial import unittest
  15. from sydent.http.auth import tokenFromRequest
  16. from tests.utils import make_request, make_sydent
  17. class AuthTestCase(unittest.TestCase):
  18. """Tests Sydent's auth code"""
  19. def setUp(self):
  20. # Create a new sydent
  21. self.sydent = make_sydent()
  22. self.test_token = "testingtoken"
  23. # Inject a fake OpenID token into the database
  24. cur = self.sydent.db.cursor()
  25. cur.execute(
  26. "INSERT INTO accounts (user_id, created_ts, consent_version)"
  27. "VALUES (?, ?, ?)",
  28. ("@bob:localhost", 101010101, "asd"),
  29. )
  30. cur.execute(
  31. "INSERT INTO tokens (user_id, token)" "VALUES (?, ?)",
  32. ("@bob:localhost", self.test_token),
  33. )
  34. self.sydent.db.commit()
  35. def test_can_read_token_from_headers(self):
  36. """Tests that Sydent correctly extracts an auth token from request headers"""
  37. self.sydent.run()
  38. request, _ = make_request(
  39. self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details"
  40. )
  41. request.requestHeaders.addRawHeader(
  42. b"Authorization", b"Bearer " + self.test_token.encode("ascii")
  43. )
  44. token = tokenFromRequest(request)
  45. self.assertEqual(token, self.test_token)
  46. def test_can_read_token_from_query_parameters(self):
  47. """Tests that Sydent correctly extracts an auth token from query parameters"""
  48. self.sydent.run()
  49. request, _ = make_request(
  50. self.sydent.reactor,
  51. "GET",
  52. "/_matrix/identity/v2/hash_details?access_token=" + self.test_token,
  53. )
  54. token = tokenFromRequest(request)
  55. self.assertEqual(token, self.test_token)