view roundup/cgi/wsgi_handler.py @ 8411:ef1ea918b07a reauth-confirm_id

feat(security): Add user confirmation/reauth for sensitive changes Auditors can raise Reauth(reason) exception to require the user to enter a token (e.g. account password) to verify the user is performing the change. Naming is subject to change. actions.py: New ReauthAction class handler and verifyPassword() method for overriding if needed. client.py: Handle Reauth exception by calling Client:reauth() method. Default client:reauth method. Add 'reauth' action declaration. exceptions.py: Define and document Reauth exception as a subclass of RoundupCGIException. templating.py: Define method utils.embed_form_fields(). The original form making a change to the database has a lot of form fields. These need to be resubmitted to Roundup as part of the form submission that verifies the user's password. This method turns all non file form fields into type=hidden inputs. It escapes the names and values to prevent XSS. For file form fields, it base64 encodes the contents and puts them in hidden pre blocks. The pre blocks have data attributes for the filename, filetype and the original field name. (Note the original field name is not used.) This stops the file content data (maybe binary e.g. jpegs) from breaking the html page. The reauth template runs JavaScript that turns the encoded data inside the pre tags back into a file. Then it adds a multiple file input control to the page and attaches all the files to it. This file input is submitted with the rest of the fields. _generic.reauth.html (multiple tracker templates): Generates a form with id=reauth_form to: display any message from the Reauth exception to the user (e.g. why user is asked to auth). get the user's password submit the form embed all the form data that triggered the reauth recreate any file data that was submitted as part of the form and generate a new file input to push the data to the back end It has the JavaScript routine (as an IIFE) that regenerates a file input without user intervention. All the TAL based tracker templates use the same form. There is also one for the jinja2 template. The JavaScript for both is the same. reference.txt: document embed_form_fields utility method. upgrading.txt: initial upgrading docs. TODO: Finalize naming. I am leaning toward ConfirmID rather than Reauth. Still looking for a standard name for this workflow. Externalize the javascript in _generic.reauth.html to a seperate file and use utils.readfile() to embed it or change the script to load it from a @@file url. Clean up upgrading.txt with just steps to implement and less feature detail/internals. Document internals/troubleshooting in reference.txt. Add tests using live server.
author John Rouillard <rouilj@ieee.org>
date Mon, 11 Aug 2025 14:01:12 -0400
parents dbeb6bf056c7
children 14c7c07b32d8
line wrap: on
line source

# WSGI interface for Roundup Issue Tracker
#
# This module is free software, you may redistribute it
# and/or modify under the same terms as Python.
#

import os
from contextlib import contextmanager

import roundup.instance
from roundup.anypy import http_
from roundup.anypy.html import html_escape
from roundup.anypy.strings import s2b
from roundup.cgi import TranslationService
from roundup.cgi.client import BinaryFieldStorage

BaseHTTPRequestHandler = http_.server.BaseHTTPRequestHandler
DEFAULT_ERROR_MESSAGE = http_.server.DEFAULT_ERROR_MESSAGE

try:
    # python2 is missing this definition
    http_.server.BaseHTTPRequestHandler.responses[429]
except KeyError:
    http_.server.BaseHTTPRequestHandler.responses[429] = (
         'Too Many Requests',
        'The user has sent too many requests in '
        'a given amount of time ("rate limiting")',
    )


class Headers(object):
    """ Idea more or less stolen from the 'apache.py' in same directory.
        Except that wsgi stores http headers in environment.
    """
    def __init__(self, environ):
        self.environ = environ

    def mangle_name(self, name):
        """ Content-Type is handled specially, it doesn't have a HTTP_
            prefix in cgi.
        """
        n = name.replace('-', '_').upper()
        if n == 'CONTENT_TYPE':
            return n
        return 'HTTP_' + n

    def get(self, name, default=None):
        return self.environ.get(self.mangle_name(name), default)
    getheader = get


class Writer(object):
    '''Perform a start_response if need be when we start writing.'''
    def __init__(self, request):
        self.request = request  # weakref.ref(request)

    def write(self, data):
        f = self.request.get_wfile()
        self.write = f
        return self.write(data)


class RequestHandler(object):
    def __init__(self, environ, start_response):
        self.__start_response = start_response
        self.__wfile = None
        self.headers = Headers(environ)
        self.rfile, self.wfile = None, Writer(self)

    def start_response(self, headers, response_code):
        """Set HTTP response code"""
        message, _explain = BaseHTTPRequestHandler.responses[response_code]
        self.__wfile = self.__start_response('%d %s' % (response_code,
                                                        message), headers)

    def get_wfile(self):
        if self.__wfile is None:
            raise ValueError('start_response() not called')
        return self.__wfile


class RequestDispatcher(object):
    def __init__(self, home, debug=False, timing=False, lang=None,
                 feature_flags=None):
        if not os.path.isdir(home):
            raise ValueError('%r is not a directory' % (home,))
        self.home = home
        self.debug = debug
        self.timing = timing
        self.feature_flags = feature_flags or {}
        self.tracker = None
        if lang:
            self.translator = TranslationService.get_translation(
                lang,
                tracker_home=home)
        else:
            self.translator = None

        if "cache_tracker" not in self.feature_flags or \
           self.feature_flags["cache_tracker"] is not False:
            self.tracker = roundup.instance.open(self.home, not self.debug)
        else:
            self.preload()

    def __call__(self, environ, start_response):
        """Initialize with `apache.Request` object"""
        request = RequestHandler(environ, start_response)

        if environ['REQUEST_METHOD'] == 'OPTIONS':
            if environ["PATH_INFO"][:5] == "/rest":
                # rest does support options
                # This I hope will result in self.form=None
                environ['CONTENT_LENGTH'] = 0
            else:
                code = 501
                message, explain = BaseHTTPRequestHandler.responses[code]
                request.start_response([('Content-Type', 'text/html')],
                                       code)
                request.wfile.write(s2b(DEFAULT_ERROR_MESSAGE % locals()))
                return []

        # need to strip the leading '/'
        environ["PATH_INFO"] = environ["PATH_INFO"][1:]
        if self.timing:
            environ["CGI_SHOW_TIMING"] = self.timing

        if environ['REQUEST_METHOD'] in ("OPTIONS", "DELETE"):
            # these methods have no data. When we init tracker.Client
            # set form to None to get a properly initialized empty
            # form.
            form = None
        else:
            form = BinaryFieldStorage(fp=environ['wsgi.input'], environ=environ)

        if "cache_tracker" not in self.feature_flags or \
           self.feature_flags["cache_tracker"] is not False:
            client = self.tracker.Client(self.tracker, request, environ, form,
                                         self.translator)
            try:
                client.main()
            except roundup.cgi.client.NotFound:
                request.start_response([('Content-Type', 'text/html')], 404)
                request.wfile.write(s2b('Not found: %s' %
                                        html_escape(client.path)))
        else:
            with self.get_tracker() as tracker:
                client = tracker.Client(tracker, request, environ, form,
                                        self.translator)
                try:
                    client.main()
                except roundup.cgi.client.NotFound:
                    request.start_response([('Content-Type', 'text/html')], 404)
                    request.wfile.write(s2b('Not found: %s' %
                                            html_escape(client.path)))

        # all body data has been written using wfile
        return []

    def preload(self):
        """ Trigger pre-loading of imports and templates """
        with self.get_tracker():
            pass

    @contextmanager
    def get_tracker(self):
        # get a new instance for each request
        yield roundup.instance.open(self.home, not self.debug)

Roundup Issue Tracker: http://roundup-tracker.org/