From 0208b1218c4eb4236f149bfe7e8f9e08fab4cce1 Mon Sep 17 00:00:00 2001 From: jk464 Date: Tue, 1 Dec 2026 14:18:07 +0000 Subject: [PATCH 1/2] Fix gevent WSGI server running requests in the hub greenlet concurrency.wsgi_server() always passed spawn=custom_pool to gevent's WSGIServer. st2auth passes no pool, so gevent received spawn=None, which makes it call the request handler synchronously in the hub greenlet. Anything that then has to switch to the hub fails with BlockingSwitchOutError: with pymongo that is opening a new connection and resolving the host through gevent's thread resolver, so POST /tokens returned HTTP 500 whenever the connection pool needed a new connection. st2api and st2stream always pass a pool and are not affected. Only pass spawn when a pool was given, so gevent spawns a greenlet per request. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.rst | 1 + st2common/st2common/util/concurrency.py | 11 ++-- st2common/tests/unit/test_concurrency.py | 69 ++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 st2common/tests/unit/test_concurrency.py diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 915058eff0..da52723f77 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -22,6 +22,7 @@ Redis 8.6 Fixed ~~~~~ +* Fix ``st2auth`` returning HTTP 500 on ``POST /tokens`` when running with gevent (``BlockingSwitchOutError``). ``concurrency.wsgi_server()`` passed ``spawn=None`` to gevent's ``WSGIServer`` when no pool was given, which made it run every request in the hub greenlet instead of a greenlet of its own. #6426 (by @jk464 and Claude Sonnet 5.5) * Fix ``TypeError`` when displaying help for actions whose parameters have no ``description`` key. #6375 * Fix utf-8 encode before checking paramter max size #6352 * Fix stuck running workflow tasks #6398 (by @guzzijones12@gmail.com) diff --git a/st2common/st2common/util/concurrency.py b/st2common/st2common/util/concurrency.py index 50f9c3442f..e13b248fd7 100644 --- a/st2common/st2common/util/concurrency.py +++ b/st2common/st2common/util/concurrency.py @@ -135,9 +135,14 @@ def wsgi_server( **kwargs, ) elif _state.library == "gevent": - server = _state.gevent.pywsgi.WSGIServer( - socket, app, spawn=custom_pool, log=log - ) + # NOTE: An explicit spawn=None makes gevent run each request handler synchronously + # inside the hub greenlet, where anything which needs to switch to the hub (DNS + # lookup when opening a new DB connection, sleep, ...) fails with + # BlockingSwitchOutError. Leaving spawn out gives each request its own greenlet. + server_kwargs = {} + if custom_pool is not None: + server_kwargs["spawn"] = custom_pool + server = _state.gevent.pywsgi.WSGIServer(socket, app, log=log, **server_kwargs) server.serve_forever() else: raise ValueError(f"Unsupported concurrency library {_state.library}") diff --git a/st2common/tests/unit/test_concurrency.py b/st2common/tests/unit/test_concurrency.py new file mode 100644 index 0000000000..7fb129e572 --- /dev/null +++ b/st2common/tests/unit/test_concurrency.py @@ -0,0 +1,69 @@ +# Copyright 2020-2026 The StackStorm Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Tests for the wsgi_server() compatibility wrapper, which has to work with whichever +concurrency library is configured. +""" + +import http.client +import unittest + +from st2common.util import concurrency + + +def app(environ, start_response): + # Anything which needs to switch to the event loop fails if the request is being handled in + # the gevent hub greenlet itself (e.g. a DNS lookup when the DB layer opens a new connection) + concurrency.sleep(0.01) + start_response("200 OK", [("Content-Type", "text/plain")]) + return [b"ok"] + + +class WSGIServerTestCase(unittest.TestCase): + def setUp(self): + super().setUp() + self.sock = concurrency.listen_server("127.0.0.1", 0) + self.port = self.sock.getsockname()[1] + self.server = None + + def tearDown(self): + if self.server: + concurrency.kill(self.server) + self.sock.close() + super().tearDown() + + def _start(self, **kwargs): + self.server = concurrency.spawn( + concurrency.wsgi_server, self.sock, app, log_output=False, **kwargs + ) + concurrency.sleep(0.1) + + def _get(self): + conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + try: + conn.request("GET", "/") + response = conn.getresponse() + return response.status, response.read() + finally: + conn.close() + + def test_http(self): + self._start() + self.assertEqual(self._get(), (200, b"ok")) + + def test_http_custom_pool(self): + pool = concurrency.get_green_pool_class()(10) + self._start(custom_pool=pool) + self.assertEqual(self._get(), (200, b"ok")) From 7ba9eecca0a35af9b06e1c7e6b7fb3d88f46ad32 Mon Sep 17 00:00:00 2001 From: jk464 Date: Tue, 1 Dec 2026 14:18:12 +0000 Subject: [PATCH 2/2] Fix st2auth TLS under gevent: let WSGIServer do the TLS wrapping st2auth wrapped its listening socket with concurrency.wrap_ssl() and handed the SSLSocket to wsgi_server(). gevent's WSGIServer requires a plain listening socket and does the TLS handshake itself, per accepted connection, so with [auth] use_ssl = True st2auth crashed at startup with "TypeError: Expected a regular socket, not SSLSocket". wsgi_server() now takes certfile and keyfile. Under eventlet it still wraps the socket with eventlet.wrap_ssl(); under gevent it passes an ssl_context to WSGIServer. st2auth passes the files instead of wrapping the socket. The HTTPS tests verify the server certificate: the client trusts only the fixture CA and checks the host name, and there are negative tests for an untrusted CA and a wrong host name (both must raise SSLCertVerificationError). They run on both gevent and eventlet. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.rst | 1 + st2auth/st2auth/cmd/api.py | 10 ++-- st2common/st2common/util/concurrency.py | 34 ++++++++++++- st2common/tests/unit/test_concurrency.py | 63 ++++++++++++++++++++++-- 4 files changed, 98 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index da52723f77..251e72bc41 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -23,6 +23,7 @@ Redis 8.6 Fixed ~~~~~ * Fix ``st2auth`` returning HTTP 500 on ``POST /tokens`` when running with gevent (``BlockingSwitchOutError``). ``concurrency.wsgi_server()`` passed ``spawn=None`` to gevent's ``WSGIServer`` when no pool was given, which made it run every request in the hub greenlet instead of a greenlet of its own. #6426 (by @jk464 and Claude Sonnet 5.5) +* Fix ``st2auth`` failing to start with ``[auth] use_ssl = True`` when running with gevent (``TypeError: Expected a regular socket, not SSLSocket``). ``concurrency.wsgi_server()`` now takes ``certfile`` and ``keyfile`` and does the TLS wrapping itself, as gevent requires. #6426 (by @jk464 and Claude Sonnet 5.5) * Fix ``TypeError`` when displaying help for actions whose parameters have no ``description`` key. #6375 * Fix utf-8 encode before checking paramter max size #6352 * Fix stuck running workflow tasks #6398 (by @guzzijones12@gmail.com) diff --git a/st2auth/st2auth/cmd/api.py b/st2auth/st2auth/cmd/api.py index 27554efb64..5bc6067e63 100644 --- a/st2auth/st2auth/cmd/api.py +++ b/st2auth/st2auth/cmd/api.py @@ -84,11 +84,11 @@ def _run_server(): if not os.path.isfile(key_file_path): raise ValueError(f'Private key file "{key_file_path}" does not exist') - socket = concurrency.wrap_ssl( - socket, certfile=cert_file_path, keyfile=key_file_path, server_side=True - ) + # TLS is handled by the WSGI server itself (see concurrency.wsgi_server) + ssl_kwargs = {"certfile": cert_file_path, "keyfile": key_file_path} else: scheme = "http" + ssl_kwargs = {} LOG.info('ST2 Auth API running in "%s" auth mode', cfg.CONF.auth.mode) LOG.info( @@ -99,7 +99,9 @@ def _run_server(): port, ) - concurrency.wsgi_server(socket, app.setup_app(), log=LOG, log_output=False) + concurrency.wsgi_server( + socket, app.setup_app(), log=LOG, log_output=False, **ssl_kwargs + ) return 0 diff --git a/st2common/st2common/util/concurrency.py b/st2common/st2common/util/concurrency.py index e13b248fd7..5289f7c320 100644 --- a/st2common/st2common/util/concurrency.py +++ b/st2common/st2common/util/concurrency.py @@ -122,9 +122,30 @@ def get_subprocess_module(): def wsgi_server( - socket, app, custom_pool=None, log=None, log_output=True, *args, **kwargs + socket, + app, + custom_pool=None, + log=None, + log_output=True, + certfile=None, + keyfile=None, + *args, + **kwargs, ): + """ + Serve a WSGI app on the provided listening socket. + + :param certfile: Path to the TLS certificate. If provided, the server serves HTTPS. + The socket passed in must be a plain (not TLS wrapped) listening socket + because gevent does the TLS handshake itself, per accepted connection. + :param keyfile: Path to the TLS private key matching ``certfile`` (can be None if the key + is in the certfile). + """ if _state.library == "eventlet": + if certfile: + socket = _state.eventlet.wrap_ssl( + socket, certfile=certfile, keyfile=keyfile, server_side=True + ) _state.eventlet.wsgi.server( socket, app, @@ -135,13 +156,20 @@ def wsgi_server( **kwargs, ) elif _state.library == "gevent": + server_kwargs = {} # NOTE: An explicit spawn=None makes gevent run each request handler synchronously # inside the hub greenlet, where anything which needs to switch to the hub (DNS # lookup when opening a new DB connection, sleep, ...) fails with # BlockingSwitchOutError. Leaving spawn out gives each request its own greenlet. - server_kwargs = {} if custom_pool is not None: server_kwargs["spawn"] = custom_pool + if certfile: + import ssl + + # Monkey patching must have happened prior to this so the context is green + context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + context.load_cert_chain(certfile, keyfile) + server_kwargs["ssl_context"] = context server = _state.gevent.pywsgi.WSGIServer(socket, app, log=log, **server_kwargs) server.serve_forever() else: @@ -388,6 +416,8 @@ def listen_server(host, port, backlog=50, **kwargs): def wrap_ssl(socket, *args, **kwargs): + # NOTE: Do not use this to wrap the listening socket of a WSGI server, pass certfile and + # keyfile to wsgi_server() instead. gevent's WSGIServer refuses an already wrapped socket. if _state.library == "eventlet": return _state.eventlet.wrap_ssl(socket, *args, **kwargs) elif _state.library == "gevent": diff --git a/st2common/tests/unit/test_concurrency.py b/st2common/tests/unit/test_concurrency.py index 7fb129e572..707e6fc835 100644 --- a/st2common/tests/unit/test_concurrency.py +++ b/st2common/tests/unit/test_concurrency.py @@ -14,13 +14,23 @@ """ Tests for the wsgi_server() compatibility wrapper, which has to work with whichever -concurrency library is configured. +concurrency library is configured, with and without TLS. """ import http.client +import os +import socket +import ssl import unittest from st2common.util import concurrency +from st2tests.fixtures.ssl_certs.fixture import FIXTURE_PATH as CERTS_FIXTURES_PATH + +CERT_FILE = os.path.join(CERTS_FIXTURES_PATH, "server", "server_certificate.pem") +KEY_FILE = os.path.join(CERTS_FIXTURES_PATH, "server", "private_key.pem") +CA_FILE = os.path.join(CERTS_FIXTURES_PATH, "ca", "ca_certificate_bundle.pem") +# The fixture server certificate is issued by the fixture CA to CN=localhost (no SAN) +SERVER_HOSTNAME = "localhost" def app(environ, start_response): @@ -50,8 +60,25 @@ def _start(self, **kwargs): ) concurrency.sleep(0.1) - def _get(self): + def _get(self, https, cafile=CA_FILE, server_hostname=SERVER_HOSTNAME): + """ + Make a GET request. HTTPS connections verify the server certificate against ``cafile`` + (or only the system trust store if it is None) and check it was issued for + ``server_hostname``. The connection itself always goes to the loopback address. + """ conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + if https: + context = ssl.create_default_context(cafile=cafile) + # The fixture certificate only has a common name, no subjectAltName + context.hostname_checks_common_name = True + self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED) + self.assertTrue(context.check_hostname) + sock = socket.create_connection(("127.0.0.1", self.port), timeout=10) + try: + conn.sock = context.wrap_socket(sock, server_hostname=server_hostname) + except BaseException: + sock.close() + raise try: conn.request("GET", "/") response = conn.getresponse() @@ -61,9 +88,37 @@ def _get(self): def test_http(self): self._start() - self.assertEqual(self._get(), (200, b"ok")) + self.assertEqual(self._get(https=False), (200, b"ok")) def test_http_custom_pool(self): pool = concurrency.get_green_pool_class()(10) self._start(custom_pool=pool) - self.assertEqual(self._get(), (200, b"ok")) + self.assertEqual(self._get(https=False), (200, b"ok")) + + def test_https(self): + # The listening socket is a plain socket, the server does the TLS handshake. The client + # verifies the certificate chain against the fixture CA and the host name. + self._start(certfile=CERT_FILE, keyfile=KEY_FILE) + self.assertEqual(self._get(https=True), (200, b"ok")) + + def test_https_untrusted_ca(self): + # Without the fixture CA the certificate must not be trusted + self._start(certfile=CERT_FILE, keyfile=KEY_FILE) + with self.assertRaises(ssl.SSLCertVerificationError): + self._get(https=True, cafile=None) + # a client which refused the certificate must not take the server down + self.assertEqual(self._get(https=True), (200, b"ok")) + + def test_https_wrong_hostname(self): + # The CA is trusted but the certificate was not issued for this host name + self._start(certfile=CERT_FILE, keyfile=KEY_FILE) + with self.assertRaises(ssl.SSLCertVerificationError): + self._get(https=True, server_hostname="st2auth.example.com") + self.assertEqual(self._get(https=True), (200, b"ok")) + + def test_https_rejects_plain_http(self): + self._start(certfile=CERT_FILE, keyfile=KEY_FILE) + with self.assertRaises((http.client.HTTPException, OSError)): + self._get(https=False) + # a client speaking the wrong protocol must not take the server down + self.assertEqual(self._get(https=True), (200, b"ok"))