|
| 1 | +# Copyright 2015 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +"""WSGI middleware to wrap the dispatcher, and supporting functions.""" |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | + |
| 20 | + |
| 21 | +RESERVED_ENV_KEYS = { |
| 22 | + 'AUTH_DOMAIN': 'gmail.com', # Default auth domain must be set. |
| 23 | + 'DATACENTER': '', |
| 24 | + 'DEFAULT_VERSION_HOSTNAME': '', |
| 25 | + 'HTTPS': '', |
| 26 | + 'REMOTE_ADDR': '', |
| 27 | + 'REQUEST_ID_HASH': '', |
| 28 | + 'REQUEST_LOG_ID': '', |
| 29 | + 'USER_EMAIL': '', |
| 30 | + 'USER_ID': '', |
| 31 | + 'USER_IS_ADMIN': '0', # Default admin flag to explicit '0'. |
| 32 | + 'USER_NICKNAME': '', |
| 33 | + 'USER_ORGANIZATION': '',} |
| 34 | + |
| 35 | + |
| 36 | +def reset_environment_middleware(app, frozen_environment, frozen_user_env, |
| 37 | + frozen_appengine_config_env): |
| 38 | + """Replace the contents of os.environ with a frozen env + request data. |
| 39 | +
|
| 40 | + This requires a single-threaded webserver, or for os.environ to be patched to |
| 41 | + be thread-local. |
| 42 | +
|
| 43 | + Args: |
| 44 | + app: The WSGI app to wrap. |
| 45 | + frozen_environment: An iterable of (key, value) tuples that can be used to |
| 46 | + populate os.environ with the initial state of the environment. |
| 47 | + `tuple(os.environ.iteritems())` produces appropriate output. |
| 48 | + frozen_user_env: An iterable of (key, value) tuples that can be used to |
| 49 | + populate os.environ with environment variables specified in app.yaml. |
| 50 | + frozen_appengine_config_env: An iterable of (key, value) tuples that can be |
| 51 | + used to populate os.environ with configuration-dependent env variables. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + The wrapped app, also a WSGI app. |
| 55 | + """ |
| 56 | + |
| 57 | + def reset_environment_wrapper(wsgi_env, start_response): # pylint: disable=missing-docstring |
| 58 | + # Wipe os.environ entirely. |
| 59 | + os.environ.clear() |
| 60 | + |
| 61 | + # Populate os.environ in order, so that later steps overwrite conflicting |
| 62 | + # keys in previous steps. |
| 63 | + |
| 64 | + # Add in user env variables specified in app.yaml. These are added first |
| 65 | + # because they should not take precedence over any conflicting key. |
| 66 | + os.environ.update(frozen_user_env) |
| 67 | + |
| 68 | + # Repopulate os.environ with the frozen environment. |
| 69 | + os.environ.update(frozen_environment) |
| 70 | + |
| 71 | + # Add in wsgi_env data, including request headers. |
| 72 | + os.environ.update(request_environment_for_wsgi_env(wsgi_env)) |
| 73 | + |
| 74 | + # Add in configuration data from appengine_config. |
| 75 | + os.environ.update(frozen_appengine_config_env) |
| 76 | + |
| 77 | + # Add reserved keys, which draw from wsgi_env as well. These have a very |
| 78 | + # high priority and so are added nearly last. |
| 79 | + os.environ.update(reserved_env_keys_for_wsgi_env(wsgi_env)) |
| 80 | + |
| 81 | + # Tweak the environment to hide the service bridge. |
| 82 | + os.environ.update(get_env_to_hide_service_bridge(wsgi_env)) |
| 83 | + |
| 84 | + return app(wsgi_env, start_response) |
| 85 | + |
| 86 | + return reset_environment_wrapper |
| 87 | + |
| 88 | + |
| 89 | +def request_environment_for_wsgi_env(wsgi_env): |
| 90 | + """Get a dict of key-value pairs from wsgi_env that work as env variables. |
| 91 | +
|
| 92 | + Does not mutate input. |
| 93 | +
|
| 94 | + Args: |
| 95 | + wsgi_env: WSGI request env data. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + A dictionary suitable for use in `os.environ.update(output)`. |
| 99 | + """ |
| 100 | + |
| 101 | + # Return all key, value pairs from wsgi_env where value is a string. |
| 102 | + return {key: value for key, value in wsgi_env.iteritems() |
| 103 | + if isinstance(value, basestring)} |
| 104 | + |
| 105 | + |
| 106 | +def reserved_env_keys_for_wsgi_env(wsgi_env): |
| 107 | + """Get a dict for reserved keys based on wsgi_env headers and defaults. |
| 108 | +
|
| 109 | + Does not mutate input. |
| 110 | +
|
| 111 | + Args: |
| 112 | + wsgi_env: WSGI request env data. |
| 113 | +
|
| 114 | + Returns: |
| 115 | + A dictionary suitable for use in `os.environ.update(output)`. |
| 116 | + """ |
| 117 | + |
| 118 | + output = {} |
| 119 | + |
| 120 | + # Use the default value for a reserved key if the corresponding header is not |
| 121 | + # set, or if the header exists but its value is blank. |
| 122 | + for key, default in RESERVED_ENV_KEYS.iteritems(): |
| 123 | + value = wsgi_env.get('HTTP_X_APPENGINE_' + key) |
| 124 | + output[key] = value or default # Must be set to a valid value or default. |
| 125 | + |
| 126 | + return output |
| 127 | + |
| 128 | + |
| 129 | +def get_env_to_hide_service_bridge(wsgi_env): |
| 130 | + """Generate a dictionary of environment variables to hide the service bridge. |
| 131 | +
|
| 132 | + Does not mutate input. |
| 133 | +
|
| 134 | + Args: |
| 135 | + wsgi_env: WSGI request env data. |
| 136 | +
|
| 137 | + Returns: |
| 138 | + A dictionary suitable for use in `os.environ.update(output)`. |
| 139 | + """ |
| 140 | + output = {} |
| 141 | + |
| 142 | + # Because the request is coming over the service bridge, the service bridge |
| 143 | + # host and port that are automatically populated in SERVER_NAME and |
| 144 | + # SERVER_PORT, respectively. However, this is an implementation detail that |
| 145 | + # should not be shown to user code. Instead, we'll rely on the HTTP Host |
| 146 | + # header to retrieve the hostname used in the original request. This mimics |
| 147 | + # the behavior of non-VM App Engine. |
| 148 | + if 'HTTP_HOST' in wsgi_env: |
| 149 | + output['SERVER_NAME'] = wsgi_env['HTTP_HOST'] |
| 150 | + |
| 151 | + # Similarly we'll use the HTTPS flag to determine the port used in the |
| 152 | + # original request. |
| 153 | + https = wsgi_env.get('HTTP_X_APPENGINE_HTTPS', 'off') |
| 154 | + if https == 'off': |
| 155 | + output['SERVER_PORT'] = '80' |
| 156 | + elif https == 'on': |
| 157 | + output['SERVER_PORT'] = '443' |
| 158 | + else: |
| 159 | + logging.warning('Unrecognized value for HTTPS (%s), won\'t modify ' |
| 160 | + 'SERVER_PORT', https) |
| 161 | + |
| 162 | + return output |
0 commit comments