Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ 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)
Expand Down
10 changes: 6 additions & 4 deletions st2auth/st2auth/cmd/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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


Expand Down
43 changes: 39 additions & 4 deletions st2common/st2common/util/concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -135,9 +156,21 @@ def wsgi_server(
**kwargs,
)
elif _state.library == "gevent":
server = _state.gevent.pywsgi.WSGIServer(
socket, app, spawn=custom_pool, log=log
)
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.
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:
raise ValueError(f"Unsupported concurrency library {_state.library}")
Expand Down Expand Up @@ -383,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":
Expand Down
124 changes: 124 additions & 0 deletions st2common/tests/unit/test_concurrency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# 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, 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):
# 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, 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()
return response.status, response.read()
finally:
conn.close()

def test_http(self):
self._start()
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(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"))
Loading