|
| 1 | +""" |
| 2 | +The development server looks for an environment.yaml in the given directory and reads the Functions from it. |
| 3 | +The Functions are then available via HTTP requests to the server. |
| 4 | +
|
| 5 | +The server will automatically restart if you make changes to your Functions code or to the `environment.yaml` file. |
| 6 | +
|
| 7 | +Usage: |
| 8 | +
|
| 9 | +```bash |
| 10 | +python -m csfunctions.devserver |
| 11 | +``` |
| 12 | +
|
| 13 | +Optional arguments: |
| 14 | +
|
| 15 | +--dir <directory> |
| 16 | + The directory containing the environment.yaml file. |
| 17 | + (default: current working directory) |
| 18 | +
|
| 19 | +--secret <secret> |
| 20 | + The secret token to use for the development server. |
| 21 | +
|
| 22 | +--port <port> |
| 23 | + The port to run the development server on. |
| 24 | + (default: 8000) |
| 25 | +
|
| 26 | +--no-reload |
| 27 | + Disable auto reloading of the server. |
| 28 | +""" |
| 29 | + |
| 30 | +import argparse |
| 31 | +import hashlib |
| 32 | +import hmac |
| 33 | +import json |
| 34 | +import logging |
| 35 | +import os |
| 36 | +import time |
| 37 | +from collections.abc import Iterable |
| 38 | +from wsgiref.types import StartResponse, WSGIEnvironment |
| 39 | + |
| 40 | +from werkzeug.serving import run_simple |
| 41 | +from werkzeug.wrappers import Request, Response |
| 42 | + |
| 43 | +from csfunctions.handler import FunctionNotRegistered, execute |
| 44 | + |
| 45 | + |
| 46 | +def _is_error_response(function_response: str | dict): |
| 47 | + """ |
| 48 | + Try to figure out if the response from the function is an error response. |
| 49 | + This is the same implementation as in the runtime, to ensure the behavior is the same. |
| 50 | + """ |
| 51 | + if isinstance(function_response, str): |
| 52 | + # function response could be a json encoded dict, so we try to decode it first |
| 53 | + try: |
| 54 | + function_response = json.loads(function_response) |
| 55 | + except json.JSONDecodeError: |
| 56 | + # response is not json decoded, so it's not an error response |
| 57 | + return False |
| 58 | + |
| 59 | + if isinstance(function_response, dict): |
| 60 | + # check if the response dict is an error response |
| 61 | + return function_response.get("response_type") == "error" |
| 62 | + else: |
| 63 | + # function response is neither a dict nor json encoded dict, so can't be an error response |
| 64 | + return False |
| 65 | + |
| 66 | + |
| 67 | +def _verify_hmac_signature( |
| 68 | + signature: str | None, timestamp: str | None, body: str, secret_token: str, max_age: int = 60 |
| 69 | +) -> bool: |
| 70 | + """ |
| 71 | + Verify the HMAC signature of the request. |
| 72 | + If timestamp is older than max_age seconds, the request is rejected. (default: 60 seconds, disable with -1) |
| 73 | + """ |
| 74 | + if not secret_token: |
| 75 | + # this should not happen, since this function should only be called if a secret token is set |
| 76 | + raise ValueError("Missing secret token") |
| 77 | + |
| 78 | + if not signature: |
| 79 | + logging.warning("Request does not contain a signature") |
| 80 | + return False |
| 81 | + |
| 82 | + if not timestamp: |
| 83 | + logging.warning("Request does not contain a timestamp") |
| 84 | + return False |
| 85 | + |
| 86 | + if max_age >= 0 and int(timestamp) < time.time() - max_age: |
| 87 | + logging.warning("Timestamp of request is older than %d seconds", max_age) |
| 88 | + return False |
| 89 | + |
| 90 | + return hmac.compare_digest( |
| 91 | + signature, |
| 92 | + hmac.new( |
| 93 | + secret_token.encode("utf-8"), |
| 94 | + f"{timestamp}{body}".encode(), |
| 95 | + hashlib.sha256, |
| 96 | + ).hexdigest(), |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +def handle_request(request: Request) -> Response: |
| 101 | + """ |
| 102 | + Handles a request to the development server. |
| 103 | + Extracts the function name from the request path and executes the Function using the execute handler. |
| 104 | + """ |
| 105 | + function_name = request.path.strip("/") |
| 106 | + if not function_name: |
| 107 | + return Response("No function name provided", status=400) |
| 108 | + body = request.get_data(as_text=True) |
| 109 | + signature = request.headers.get("X-CON-Signature-256") |
| 110 | + timestamp = request.headers.get("X-CON-Timestamp") |
| 111 | + |
| 112 | + secret_token = os.environ.get("CON_DEV_SECRET", "") |
| 113 | + if secret_token and not _verify_hmac_signature(signature, timestamp, body, secret_token): |
| 114 | + return Response("Invalid signature", status=401) |
| 115 | + |
| 116 | + try: |
| 117 | + function_dir = os.environ.get("CON_DEV_DIR", "") |
| 118 | + logging.info("Executing function: %s", function_name) |
| 119 | + response = execute(function_name, body, function_dir=function_dir) |
| 120 | + except FunctionNotRegistered as e: |
| 121 | + logging.warning("Function not found: %s", function_name) |
| 122 | + return Response(str(e), status=404) |
| 123 | + |
| 124 | + if _is_error_response(response): |
| 125 | + logging.error("Function %s returned error response", function_name) |
| 126 | + return Response(response, status=500, content_type="application/json") |
| 127 | + |
| 128 | + return Response(response, content_type="application/json") |
| 129 | + |
| 130 | + |
| 131 | +def application(environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: |
| 132 | + request = Request(environ) |
| 133 | + response = handle_request(request) |
| 134 | + return response(environ, start_response) |
| 135 | + |
| 136 | + |
| 137 | +def run_server() -> None: |
| 138 | + port = int(os.environ.get("CON_DEV_PORT", 8000)) |
| 139 | + if not 1 <= port <= 65535: |
| 140 | + raise ValueError(f"Invalid port number: {port}") |
| 141 | + |
| 142 | + logging.info("Starting development server on port %d", port) |
| 143 | + # B104: binding to all interfaces is intentional - this is a development server |
| 144 | + run_simple( |
| 145 | + "0.0.0.0", # nosec: B104 |
| 146 | + port, |
| 147 | + application, |
| 148 | + use_reloader=not bool(os.environ.get("CON_DEV_NO_RELOAD")), |
| 149 | + extra_files=[os.path.join(os.environ.get("CON_DEV_DIR", ""), "environment.yaml")], |
| 150 | + ) |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + logging.basicConfig(level=logging.INFO) |
| 155 | + |
| 156 | + parser = argparse.ArgumentParser() |
| 157 | + parser.add_argument( |
| 158 | + "--dir", |
| 159 | + type=str, |
| 160 | + help="The directory containing the environment.yaml file. (default: current working directory)", |
| 161 | + ) |
| 162 | + parser.add_argument( |
| 163 | + "--secret", |
| 164 | + type=str, |
| 165 | + help="The secret token to use for the development server.", |
| 166 | + ) |
| 167 | + parser.add_argument("--port", type=int, help="The port to run the development server on. (default: 8000)") |
| 168 | + parser.add_argument("--no-reload", action="store_true", help="Disable auto reloading of the server.") |
| 169 | + args = parser.parse_args() |
| 170 | + |
| 171 | + # Command line arguments take precedence over environment variables |
| 172 | + if args.dir: |
| 173 | + os.environ["CON_DEV_DIR"] = args.dir |
| 174 | + if args.secret: |
| 175 | + os.environ["CON_DEV_SECRET"] = args.secret |
| 176 | + if args.port: |
| 177 | + os.environ["CON_DEV_PORT"] = str(args.port) |
| 178 | + if args.no_reload: |
| 179 | + os.environ["CON_DEV_NO_RELOAD"] = "1" |
| 180 | + |
| 181 | + if not os.environ.get("CON_DEV_SECRET"): |
| 182 | + logging.warning( |
| 183 | + "\033[91m\033[1mNo secret token provided, development server is not secured!" |
| 184 | + " It is recommended to provide a secret via --secret <secret> to" |
| 185 | + " enable HMAC validation.\033[0m" |
| 186 | + ) |
| 187 | + |
| 188 | + run_server() |
0 commit comments