Skip to content
Myr

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

3 files+159 added−8 removed

modified:flask/cli.py+93 added-6 removed
12 unmodified lines
13import ast14import inspect15import os16import re17import ssl18import sys19import traceback20from functools import update_wrapper21from operator import attrgetter22from threading import Lock, Thread2324import click25from werkzeug.utils import import_string2627from . import __version__26from ._compat import getargspec, iteritems, reraise28from ._compat import getargspec, iteritems, reraise, text_type29from .globals import current_app30from .helpers import get_debug_flag, get_env3132try:
567 unmodified lines
600 if debug is not None:601 print(' * Debug mode: {0}'.format('on' if debug else 'off'))602603604class 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 """609610 name = 'path'611612 def __init__(self):613 self.path_type = click.Path(614 exists=True, dir_okay=False, resolve_path=True)615616 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()621622 if value == 'adhoc':623 try:624 import OpenSSL625 except ImportError:626 raise click.BadParameter(627 'Using ad-hoc certificates requires pyOpenSSL.',628 ctx, param)629630 return value631632 obj = import_string(value, silent=True)633634 if sys.version_info < (2, 7):635 if obj:636 return obj637 else:638 if isinstance(obj, ssl.SSLContext):639 return obj640641 raise642643644def _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'650651 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)655656 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)661662 if is_context:663 raise click.BadParameter(664 'When "--cert" is an SSLContext object, "--key is not used.',665 ctx, param)666667 if not cert:668 raise click.BadParameter(669 '"--cert" must also be specified.',670 ctx, param)671672 ctx.params['cert'] = cert, value673674 else:675 if cert and not (is_adhoc or is_context):676 raise click.BadParameter(677 'Required when using "--cert".',678 ctx, param)679680 return value681682683@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_info706def run_command(info, host, port, reload, debugger, eager_loading,620 with_threads):707 with_threads, cert):708 """Run a local development server.709710 This server is for development purposes only. It does not provide711 the stability, security, or performance of production WSGI servers.
16 unmodified lines
728 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)729730 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)733734735@click.command('shell', short_help='Runs a shell in the app context.')736@with_appcontext
119 unmodified lines
modified:tests/test_cli.py+63 added-2 removed
12 unmodified lines
13#14from __future__ import absolute_import1516import os17import ssl18import sys19import types20from functools import partial2122import click23import pytest
1 unmodified line
25from click.testing import CliRunner2627from flask import Flask, current_app28from 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)3334cwd = os.getcwd()
430 unmodified lines
465 monkeypatch.setattr('flask.cli.dotenv', None)466 monkeypatch.chdir(test_path)467 load_dotenv()468 assert 'FOO' not in os.environ469470471def test_run_cert_path():472 # no key473 with pytest.raises(click.BadParameter):474 run_command.make_context('run', ['--cert', __file__])475476 # no cert477 with pytest.raises(click.BadParameter):478 run_command.make_context('run', ['--key', __file__])479480 ctx = run_command.make_context(481 'run', ['--cert', __file__, '--key', __file__])482 assert ctx.params['cert'] == (__file__, __file__)483484485def test_run_cert_adhoc(monkeypatch):486 monkeypatch.setitem(sys.modules, 'OpenSSL', None)487488 # pyOpenSSL not installed489 with pytest.raises(click.BadParameter):490 run_command.make_context('run', ['--cert', 'adhoc'])491492 # 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'496497 # no key with adhoc498 with pytest.raises(click.BadParameter):499 run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])500501502def test_run_cert_import(monkeypatch):503 monkeypatch.setitem(sys.modules, 'not_here', None)504505 # ImportError506 with pytest.raises(click.BadParameter):507 run_command.make_context('run', ['--cert', 'not_here'])508509 # not an SSLContext510 if sys.version_info >= (2, 7):511 with pytest.raises(click.BadParameter):512 run_command.make_context('run', ['--cert', 'flask'])513514 # SSLContext515 if sys.version_info < (2, 7):516 ssl_context = object()517 else:518 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)519520 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_context523524 # 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 lines
117- 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`_)123124.. _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/1489
28 unmodified lines
155.. _#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/2606160161162Version 0.12.3163--------------
626 unmodified lines