test_auth.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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,
  40. self.sydent.clientApiHttpServer.factory,
  41. "GET",
  42. "/_matrix/identity/v2/hash_details",
  43. )
  44. request.requestHeaders.addRawHeader(
  45. b"Authorization", b"Bearer " + self.test_token.encode("ascii")
  46. )
  47. token = tokenFromRequest(request)
  48. self.assertEqual(token, self.test_token)
  49. def test_can_read_token_from_query_parameters(self):
  50. """Tests that Sydent correctly extracts an auth token from query parameters"""
  51. self.sydent.run()
  52. request, _ = make_request(
  53. self.sydent.reactor,
  54. self.sydent.clientApiHttpServer.factory,
  55. "GET",
  56. "/_matrix/identity/v2/hash_details?access_token=" + self.test_token,
  57. )
  58. token = tokenFromRequest(request)
  59. self.assertEqual(token, self.test_token)