add HTTPS support for flask run command
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent c3a9978 · Browse files · 3 files·+159 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+159 added−8 removed
- tests:+63 added−2 removed
- other:+96 added−6 removed
Provenance
- Commit
2beedab- Tree
14eaebb- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c3a9978
3 files changed+159 added−8 removed
modified:flask/cli.py+93 added-6 removed
12 unmodified lines13 import ast14 import inspect15 import os16 import re17+import ssl18 import sys19 import traceback20 from functools import update_wrapper21 from operator import attrgetter22 from threading import Lock, Thread23 24 import click25+from werkzeug.utils import import_string26 27 from . import __version__26-from ._compat import getargspec, iteritems, reraise28+from ._compat import getargspec, iteritems, reraise, text_type29 from .globals import current_app30 from .helpers import get_debug_flag, get_env31 32 try:567 unmodified lines600 if debug is not None:601 print(' * Debug mode: {0}'.format('on' if debug else 'off'))602 603 604+class CertParamType(click.ParamType):605+ """Click option type for the ``--cert`` option. Allows either an606+ existing file, the string ``'adhoc'``, or an import for a607+ :class:`~ssl.SSLContext` object.608+ """609+610+ name = 'path'611+612+ def __init__(self):613+ self.path_type = click.Path(614+ exists=True, dir_okay=False, resolve_path=True)615+616+ def convert(self, value, param, ctx):617+ try:618+ return self.path_type(value, param, ctx)619+ except click.BadParameter:620+ value = click.STRING(value, param, ctx).lower()621+622+ if value == 'adhoc':623+ try:624+ import OpenSSL625+ except ImportError:626+ raise click.BadParameter(627+ 'Using ad-hoc certificates requires pyOpenSSL.',628+ ctx, param)629+630+ return value631+632+ obj = import_string(value, silent=True)633+634+ if sys.version_info < (2, 7):635+ if obj:636+ return obj637+ else:638+ if isinstance(obj, ssl.SSLContext):639+ return obj640+641+ raise642+643+644+def _validate_key(ctx, param, value):645+ """The ``--key`` option must be specified when ``--cert`` is a file.646+ Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.647+ """648+ cert = ctx.params.get('cert')649+ is_adhoc = cert == 'adhoc'650+651+ if sys.version_info < (2, 7):652+ is_context = cert and not isinstance(cert, (text_type, bytes))653+ else:654+ is_context = isinstance(cert, ssl.SSLContext)655+656+ if value is not None:657+ if is_adhoc:658+ raise click.BadParameter(659+ 'When "--cert" is "adhoc", "--key" is not used.',660+ ctx, param)661+662+ if is_context:663+ raise click.BadParameter(664+ 'When "--cert" is an SSLContext object, "--key is not used.',665+ ctx, param)666+667+ if not cert:668+ raise click.BadParameter(669+ '"--cert" must also be specified.',670+ ctx, param)671+672+ ctx.params['cert'] = cert, value673+674+ else:675+ if cert and not (is_adhoc or is_context):676+ raise click.BadParameter(677+ 'Required when using "--cert".',678+ ctx, param)679+680+ return value681+682+683 @click.command('run', short_help='Runs a development server.')684 @click.option('--host', '-h', default='127.0.0.1',685 help='The interface to bind to.')686 @click.option('--port', '-p', default=5000,687 help='The port to bind to.')688+@click.option('--cert', type=CertParamType(),689+ help='Specify a certificate file to use HTTPS.')690+@click.option('--key',691+ type=click.Path(exists=True, dir_okay=False, resolve_path=True),692+ callback=_validate_key, expose_value=False,693+ help='The key file to use when specifying a certificate.')694 @click.option('--reload/--no-reload', default=None,608- help='Enable or disable the reloader. By default the reloader '695+ help='Enable or disable the reloader. By default the reloader '696 'is active if debug is enabled.')697 @click.option('--debugger/--no-debugger', default=None,611- help='Enable or disable the debugger. By default the debugger '698+ help='Enable or disable the debugger. By default the debugger '699 'is active if debug is enabled.')700 @click.option('--eager-loading/--lazy-loader', default=None,614- help='Enable or disable eager loading. By default eager '701+ help='Enable or disable eager loading. By default eager '702 'loading is enabled if the reloader is disabled.')703 @click.option('--with-threads/--without-threads', default=True,704 help='Enable or disable multithreading.')705 @pass_script_info706 def run_command(info, host, port, reload, debugger, eager_loading,620- with_threads):707+ with_threads, cert):708 """Run a local development server.709 710 This server is for development purposes only. It does not provide711 the stability, security, or performance of production WSGI servers.16 unmodified lines728 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)729 730 from werkzeug.serving import run_simple731 run_simple(host, port, app, use_reloader=reload, use_debugger=debugger,645- threaded=with_threads)732+ threaded=with_threads, ssl_context=cert)733 734 735 @click.command('shell', short_help='Runs a shell in the app context.')736 @with_appcontext119 unmodified linesmodified:tests/test_cli.py+63 added-2 removed
12 unmodified lines13 #14 from __future__ import absolute_import15 16 import os17+import ssl18 import sys19+import types20 from functools import partial21 22 import click23 import pytest1 unmodified line25 from click.testing import CliRunner26 27 from flask import Flask, current_app28 from flask.cli import (27- AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv,28- find_best_app, get_version, load_dotenv, locate_app, prepare_import,29+ AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,30+ get_version, load_dotenv, locate_app, prepare_import, run_command,31 with_appcontext32 )33 34 cwd = os.getcwd()430 unmodified lines465 monkeypatch.setattr('flask.cli.dotenv', None)466 monkeypatch.chdir(test_path)467 load_dotenv()468 assert 'FOO' not in os.environ469+470+471+def test_run_cert_path():472+ # no key473+ with pytest.raises(click.BadParameter):474+ run_command.make_context('run', ['--cert', __file__])475+476+ # no cert477+ with pytest.raises(click.BadParameter):478+ run_command.make_context('run', ['--key', __file__])479+480+ ctx = run_command.make_context(481+ 'run', ['--cert', __file__, '--key', __file__])482+ assert ctx.params['cert'] == (__file__, __file__)483+484+485+def test_run_cert_adhoc(monkeypatch):486+ monkeypatch.setitem(sys.modules, 'OpenSSL', None)487+488+ # pyOpenSSL not installed489+ with pytest.raises(click.BadParameter):490+ run_command.make_context('run', ['--cert', 'adhoc'])491+492+ # pyOpenSSL installed493+ monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))494+ ctx = run_command.make_context('run', ['--cert', 'adhoc'])495+ assert ctx.params['cert'] == 'adhoc'496+497+ # no key with adhoc498+ with pytest.raises(click.BadParameter):499+ run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])500+501+502+def test_run_cert_import(monkeypatch):503+ monkeypatch.setitem(sys.modules, 'not_here', None)504+505+ # ImportError506+ with pytest.raises(click.BadParameter):507+ run_command.make_context('run', ['--cert', 'not_here'])508+509+ # not an SSLContext510+ if sys.version_info >= (2, 7):511+ with pytest.raises(click.BadParameter):512+ run_command.make_context('run', ['--cert', 'flask'])513+514+ # SSLContext515+ if sys.version_info < (2, 7):516+ ssl_context = object()517+ else:518+ ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)519+520+ monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)521+ ctx = run_command.make_context('run', ['--cert', 'ssl_context'])522+ assert ctx.params['cert'] is ssl_context523+524+ # no --key with SSLContext525+ with pytest.raises(click.BadParameter):526+ run_command.make_context(527+ 'run', ['--cert', 'ssl_context', '--key', __file__])modified:CHANGES+3 added
116 unmodified lines117 - Blueprint view function name may not contain dots. (`#2450`_)118 - The dev server now uses threads by default. (`#2529`_)119 - Loading config files with ``silent=True`` will ignore ``ENOTDIR``120 errors. (`#2581`_)121+- Pass ``--cert`` and ``--key`` options to ``flask run`` to run the122+ development server over HTTPS. (`#2606`_)123 124 .. _pallets/meta#24: https://github.com/pallets/meta/issues/24125 .. _#1421: https://github.com/pallets/flask/issues/1421126 .. _#1489: https://github.com/pallets/flask/pull/148928 unmodified lines155 .. _#2436: https://github.com/pallets/flask/pull/2436156 .. _#2450: https://github.com/pallets/flask/pull/2450157 .. _#2529: https://github.com/pallets/flask/pull/2529158 .. _#2581: https://github.com/pallets/flask/pull/2581159+.. _#2606: https://github.com/pallets/flask/pull/2606160 161 162 Version 0.12.3163 --------------626 unmodified lines