test_auth.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. from twisted.trial import unittest
  16. from sydent.http.auth import tokenFromRequest
  17. from tests.utils import make_request, make_sydent
  18. class AuthTestCase(unittest.TestCase):
  19. """Tests Sydent's auth code"""
  20. def setUp(self):
  21. # Create a new sydent
  22. self.sydent = make_sydent()
  23. self.test_token = "testingtoken"
  24. # Inject a fake OpenID token into the database
  25. cur = self.sydent.db.cursor()
  26. cur.execute(
  27. "INSERT INTO accounts (user_id, created_ts, consent_version)"
  28. "VALUES (?, ?, ?)",
  29. ("@bob:localhost", 101010101, "asd")
  30. )
  31. cur.execute(
  32. "INSERT INTO tokens (user_id, token)"
  33. "VALUES (?, ?)",
  34. ("@bob:localhost", self.test_token)
  35. )
  36. self.sydent.db.commit()
  37. def test_can_read_token_from_headers(self):
  38. """Tests that Sydent correctly extracts an auth token from request headers"""
  39. self.sydent.run()
  40. request, _ = make_request(
  41. self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details"
  42. )
  43. request.requestHeaders.addRawHeader(
  44. b"Authorization", b"Bearer " + self.test_token.encode("ascii")
  45. )
  46. token = tokenFromRequest(request)
  47. self.assertEqual(token, self.test_token)
  48. def test_can_read_token_from_query_parameters(self):
  49. """Tests that Sydent correctly extracts an auth token from query parameters"""
  50. self.sydent.run()
  51. request, _ = make_request(
  52. self.sydent.reactor, "GET",
  53. "/_matrix/identity/v2/hash_details?access_token=" + self.test_token
  54. )
  55. token = tokenFromRequest(request)
  56. self.assertEqual(token, self.test_token)