Exemplo n.º 1
0
    def __init__(self, hs: HomeServer):
        self._callback_url = hs.config.oidc_callback_url  # type: str
        self._scopes = hs.config.oidc_scopes  # type: List[str]
        self._client_auth = ClientAuth(
            hs.config.oidc_client_id,
            hs.config.oidc_client_secret,
            hs.config.oidc_client_auth_method,
        )  # type: ClientAuth
        self._client_auth_method = hs.config.oidc_client_auth_method  # type: str
        self._provider_metadata = OpenIDProviderMetadata(
            issuer=hs.config.oidc_issuer,
            authorization_endpoint=hs.config.oidc_authorization_endpoint,
            token_endpoint=hs.config.oidc_token_endpoint,
            userinfo_endpoint=hs.config.oidc_userinfo_endpoint,
            jwks_uri=hs.config.oidc_jwks_uri,
        )  # type: OpenIDProviderMetadata
        self._provider_needs_discovery = hs.config.oidc_discover  # type: bool
        self._user_mapping_provider = hs.config.oidc_user_mapping_provider_class(
            hs.config.oidc_user_mapping_provider_config
        )  # type: OidcMappingProvider
        self._skip_verification = hs.config.oidc_skip_verification  # type: bool

        self._http_client = hs.get_proxied_http_client()
        self._auth_handler = hs.get_auth_handler()
        self._registration_handler = hs.get_registration_handler()
        self._datastore = hs.get_datastore()
        self._clock = hs.get_clock()
        self._hostname = hs.hostname  # type: str
        self._server_name = hs.config.server_name  # type: str
        self._macaroon_secret_key = hs.config.macaroon_secret_key
        self._error_template = load_jinja2_templates(
            hs.config.sso_template_dir, ["sso_error.html"])[0]

        # identifier for the external_ids table
        self._auth_provider_id = "oidc"
Exemplo n.º 2
0
 def prepare(
     self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
 ) -> None:
     self.store = homeserver.get_datastores().main
     self.module_api = homeserver.get_module_api()
     self.event_creation_handler = homeserver.get_event_creation_handler()
     self.sync_handler = homeserver.get_sync_handler()
     self.auth_handler = homeserver.get_auth_handler()
Exemplo n.º 3
0
    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.auth_handler = hs.get_auth_handler()
        self.macaroon_generator = hs.get_macaroon_generator()

        # MAU tests
        # AuthBlocking reads from the hs' config on initialization. We need to
        # modify its config instead of the hs'
        self.auth_blocking = hs.get_auth_blocking()
        self.auth_blocking._max_mau_value = 50

        self.small_number_of_users = 1
        self.large_number_of_users = 100

        self.user1 = self.register_user("a_user", "pass")
Exemplo n.º 4
0
    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer):
        self.store = Mock()

        hs.datastores.main = self.store
        hs.get_auth_handler().store = self.store
        self.auth = Auth(hs)

        # AuthBlocking reads from the hs' config on initialization. We need to
        # modify its config instead of the hs'
        self.auth_blocking = AuthBlocking(hs)

        self.test_user = "******"
        self.test_token = b"_test_token_"

        # this is overridden for the appservice tests
        self.store.get_app_service_by_token = Mock(return_value=None)

        self.store.insert_client_ip = simple_async_mock(None)
        self.store.is_support_user = simple_async_mock(False)
Exemplo n.º 5
0
 def prepare(self, reactor: MemoryReactor, clock: Clock,
             hs: HomeServer) -> None:
     self.recaptcha_checker = DummyRecaptchaChecker(hs)
     auth_handler = hs.get_auth_handler()
     auth_handler.checkers[LoginType.RECAPTCHA] = self.recaptcha_checker
Exemplo n.º 6
0
def setup_test_homeserver(name="test", datastore=None, config=None, **kargs):
    """Setup a homeserver suitable for running tests against. Keyword arguments
    are passed to the Homeserver constructor. If no datastore is supplied a
    datastore backed by an in-memory sqlite db will be given to the HS.
    """
    if config is None:
        config = Mock()
        config.signing_key = [MockKey()]
        config.event_cache_size = 1
        config.enable_registration = True
        config.macaroon_secret_key = "not even a little secret"
        config.expire_access_token = False
        config.server_name = name
        config.trusted_third_party_id_servers = []
        config.room_invite_state_types = []
        config.password_providers = []
        config.worker_replication_url = ""
        config.worker_app = None
        config.email_enable_notifs = False
        config.block_non_admin_invites = False

    config.use_frozen_dicts = True
    config.database_config = {"name": "sqlite3"}
    config.ldap_enabled = False

    if "clock" not in kargs:
        kargs["clock"] = MockClock()

    if datastore is None:
        db_pool = SQLiteMemoryDbPool()
        yield db_pool.prepare()
        hs = HomeServer(name,
                        db_pool=db_pool,
                        config=config,
                        version_string="Synapse/tests",
                        database_engine=create_engine(config.database_config),
                        get_db_conn=db_pool.get_db_conn,
                        room_list_handler=object(),
                        tls_server_context_factory=Mock(),
                        **kargs)
        hs.setup()
    else:
        hs = HomeServer(name,
                        db_pool=None,
                        datastore=datastore,
                        config=config,
                        version_string="Synapse/tests",
                        database_engine=create_engine(config.database_config),
                        room_list_handler=object(),
                        tls_server_context_factory=Mock(),
                        **kargs)

    # bcrypt is far too slow to be doing in unit tests
    # Need to let the HS build an auth handler and then mess with it
    # because AuthHandler's constructor requires the HS, so we can't make one
    # beforehand and pass it in to the HS's constructor (chicken / egg)
    hs.get_auth_handler().hash = lambda p: hashlib.md5(p).hexdigest()
    hs.get_auth_handler().validate_hash = lambda p, h: hashlib.md5(
        p).hexdigest() == h

    fed = kargs.get("resource_for_federation", None)
    if fed:
        server.register_servlets(
            hs,
            resource=fed,
            authenticator=server.Authenticator(hs),
            ratelimiter=FederationRateLimiter(
                hs.get_clock(),
                window_size=hs.config.federation_rc_window_size,
                sleep_limit=hs.config.federation_rc_sleep_limit,
                sleep_msec=hs.config.federation_rc_sleep_delay,
                reject_limit=hs.config.federation_rc_reject_limit,
                concurrent_requests=hs.config.federation_rc_concurrent),
        )

    defer.returnValue(hs)
Exemplo n.º 7
0
def setup_test_homeserver(name="test", datastore=None, config=None, **kargs):
    """Setup a homeserver suitable for running tests against. Keyword arguments
    are passed to the Homeserver constructor. If no datastore is supplied a
    datastore backed by an in-memory sqlite db will be given to the HS.
    """
    if config is None:
        config = Mock()
        config.signing_key = [MockKey()]
        config.event_cache_size = 1
        config.enable_registration = True
        config.macaroon_secret_key = "not even a little secret"
        config.expire_access_token = False
        config.server_name = name
        config.trusted_third_party_id_servers = []
        config.room_invite_state_types = []
        config.password_providers = []
        config.worker_replication_url = ""
        config.worker_app = None
        config.email_enable_notifs = False
        config.block_non_admin_invites = False
        config.federation_domain_whitelist = None
        config.user_directory_search_all_users = False

        # disable user directory updates, because they get done in the
        # background, which upsets the test runner.
        config.update_user_directory = False

    config.use_frozen_dicts = True
    config.ldap_enabled = False

    if "clock" not in kargs:
        kargs["clock"] = MockClock()

    if USE_POSTGRES_FOR_TESTS:
        config.database_config = {
            "name": "psycopg2",
            "args": {
                "database": "synapse_test",
                "cp_min": 1,
                "cp_max": 5,
            },
        }
    else:
        config.database_config = {
            "name": "sqlite3",
            "args": {
                "database": ":memory:",
                "cp_min": 1,
                "cp_max": 1,
            },
        }

    db_engine = create_engine(config.database_config)

    # we need to configure the connection pool to run the on_new_connection
    # function, so that we can test code that uses custom sqlite functions
    # (like rank).
    config.database_config["args"]["cp_openfun"] = db_engine.on_new_connection

    if datastore is None:
        hs = HomeServer(name,
                        config=config,
                        db_config=config.database_config,
                        version_string="Synapse/tests",
                        database_engine=db_engine,
                        room_list_handler=object(),
                        tls_server_context_factory=Mock(),
                        **kargs)
        db_conn = hs.get_db_conn()
        # make sure that the database is empty
        if isinstance(db_engine, PostgresEngine):
            cur = db_conn.cursor()
            cur.execute(
                "SELECT tablename FROM pg_tables where schemaname='public'")
            rows = cur.fetchall()
            for r in rows:
                cur.execute("DROP TABLE %s CASCADE" % r[0])
        yield prepare_database(db_conn, db_engine, config)
        hs.setup()
    else:
        hs = HomeServer(name,
                        db_pool=None,
                        datastore=datastore,
                        config=config,
                        version_string="Synapse/tests",
                        database_engine=db_engine,
                        room_list_handler=object(),
                        tls_server_context_factory=Mock(),
                        **kargs)

    # bcrypt is far too slow to be doing in unit tests
    # Need to let the HS build an auth handler and then mess with it
    # because AuthHandler's constructor requires the HS, so we can't make one
    # beforehand and pass it in to the HS's constructor (chicken / egg)
    hs.get_auth_handler().hash = lambda p: hashlib.md5(p).hexdigest()
    hs.get_auth_handler().validate_hash = lambda p, h: hashlib.md5(
        p).hexdigest() == h

    fed = kargs.get("resource_for_federation", None)
    if fed:
        server.register_servlets(
            hs,
            resource=fed,
            authenticator=server.Authenticator(hs),
            ratelimiter=FederationRateLimiter(
                hs.get_clock(),
                window_size=hs.config.federation_rc_window_size,
                sleep_limit=hs.config.federation_rc_sleep_limit,
                sleep_msec=hs.config.federation_rc_sleep_delay,
                reject_limit=hs.config.federation_rc_reject_limit,
                concurrent_requests=hs.config.federation_rc_concurrent),
        )

    defer.returnValue(hs)
Exemplo n.º 8
0
def setup_test_homeserver(name="test", datastore=None, config=None, **kargs):
    """Setup a homeserver suitable for running tests against. Keyword arguments
    are passed to the Homeserver constructor. If no datastore is supplied a
    datastore backed by an in-memory sqlite db will be given to the HS.
    """
    if config is None:
        config = Mock()
        config.signing_key = [MockKey()]
        config.event_cache_size = 1
        config.enable_registration = True
        config.macaroon_secret_key = "not even a little secret"
        config.expire_access_token = False
        config.server_name = name
        config.trusted_third_party_id_servers = []
        config.room_invite_state_types = []

    config.use_frozen_dicts = True
    config.database_config = {"name": "sqlite3"}

    if "clock" not in kargs:
        kargs["clock"] = MockClock()

    if datastore is None:
        db_pool = SQLiteMemoryDbPool()
        yield db_pool.prepare()
        hs = HomeServer(
            name,
            db_pool=db_pool,
            config=config,
            version_string="Synapse/tests",
            database_engine=create_engine(config.database_config),
            get_db_conn=db_pool.get_db_conn,
            room_list_handler=object(),
            **kargs
        )
        hs.setup()
    else:
        hs = HomeServer(
            name,
            db_pool=None,
            datastore=datastore,
            config=config,
            version_string="Synapse/tests",
            database_engine=create_engine(config.database_config),
            room_list_handler=object(),
            **kargs
        )

    # bcrypt is far too slow to be doing in unit tests
    # Need to let the HS build an auth handler and then mess with it
    # because AuthHandler's constructor requires the HS, so we can't make one
    # beforehand and pass it in to the HS's constructor (chicken / egg)
    hs.get_auth_handler().hash = lambda p: hashlib.md5(p).hexdigest()
    hs.get_auth_handler().validate_hash = lambda p, h: hashlib.md5(p).hexdigest() == h

    fed = kargs.get("resource_for_federation", None)
    if fed:
        server.register_servlets(
            hs,
            resource=fed,
            authenticator=server.Authenticator(hs),
            ratelimiter=FederationRateLimiter(
                hs.get_clock(),
                window_size=hs.config.federation_rc_window_size,
                sleep_limit=hs.config.federation_rc_sleep_limit,
                sleep_msec=hs.config.federation_rc_sleep_delay,
                reject_limit=hs.config.federation_rc_reject_limit,
                concurrent_requests=hs.config.federation_rc_concurrent,
            ),
        )

    defer.returnValue(hs)
Exemplo n.º 9
0
def setup_test_homeserver(name="test", datastore=None, config=None, **kargs):
    """Setup a homeserver suitable for running tests against. Keyword arguments
    are passed to the Homeserver constructor. If no datastore is supplied a
    datastore backed by an in-memory sqlite db will be given to the HS.
    """
    if config is None:
        config = Mock()
        config.signing_key = [MockKey()]
        config.event_cache_size = 1
        config.enable_registration = True
        config.macaroon_secret_key = "not even a little secret"
        config.expire_access_token = False
        config.server_name = name
        config.trusted_third_party_id_servers = []
        config.room_invite_state_types = []
        config.password_providers = []
        config.worker_replication_url = ""
        config.worker_app = None
        config.email_enable_notifs = False
        config.block_non_admin_invites = False
        config.federation_domain_whitelist = None
        config.federation_rc_reject_limit = 10
        config.federation_rc_sleep_limit = 10
        config.federation_rc_concurrent = 10
        config.filter_timeline_limit = 5000
        config.user_directory_search_all_users = False

        # disable user directory updates, because they get done in the
        # background, which upsets the test runner.
        config.update_user_directory = False

    config.use_frozen_dicts = True
    config.ldap_enabled = False

    if "clock" not in kargs:
        kargs["clock"] = MockClock()

    if USE_POSTGRES_FOR_TESTS:
        config.database_config = {
            "name": "psycopg2",
            "args": {
                "database": "synapse_test",
                "cp_min": 1,
                "cp_max": 5,
            },
        }
    else:
        config.database_config = {
            "name": "sqlite3",
            "args": {
                "database": ":memory:",
                "cp_min": 1,
                "cp_max": 1,
            },
        }

    db_engine = create_engine(config.database_config)

    # we need to configure the connection pool to run the on_new_connection
    # function, so that we can test code that uses custom sqlite functions
    # (like rank).
    config.database_config["args"]["cp_openfun"] = db_engine.on_new_connection

    if datastore is None:
        hs = HomeServer(
            name, config=config,
            db_config=config.database_config,
            version_string="Synapse/tests",
            database_engine=db_engine,
            room_list_handler=object(),
            tls_server_context_factory=Mock(),
            **kargs
        )
        db_conn = hs.get_db_conn()
        # make sure that the database is empty
        if isinstance(db_engine, PostgresEngine):
            cur = db_conn.cursor()
            cur.execute("SELECT tablename FROM pg_tables where schemaname='public'")
            rows = cur.fetchall()
            for r in rows:
                cur.execute("DROP TABLE %s CASCADE" % r[0])
        yield prepare_database(db_conn, db_engine, config)
        hs.setup()
    else:
        hs = HomeServer(
            name, db_pool=None, datastore=datastore, config=config,
            version_string="Synapse/tests",
            database_engine=db_engine,
            room_list_handler=object(),
            tls_server_context_factory=Mock(),
            **kargs
        )

    # bcrypt is far too slow to be doing in unit tests
    # Need to let the HS build an auth handler and then mess with it
    # because AuthHandler's constructor requires the HS, so we can't make one
    # beforehand and pass it in to the HS's constructor (chicken / egg)
    hs.get_auth_handler().hash = lambda p: hashlib.md5(p).hexdigest()
    hs.get_auth_handler().validate_hash = lambda p, h: hashlib.md5(p).hexdigest() == h

    fed = kargs.get("resource_for_federation", None)
    if fed:
        server.register_servlets(
            hs,
            resource=fed,
            authenticator=server.Authenticator(hs),
            ratelimiter=FederationRateLimiter(
                hs.get_clock(),
                window_size=hs.config.federation_rc_window_size,
                sleep_limit=hs.config.federation_rc_sleep_limit,
                sleep_msec=hs.config.federation_rc_sleep_delay,
                reject_limit=hs.config.federation_rc_reject_limit,
                concurrent_requests=hs.config.federation_rc_concurrent
            ),
        )

    defer.returnValue(hs)