Coverage for pyngrok/ngrok.py: 87.91%
215 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-19 14:11 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-19 14:11 +0000
1import json
2import logging
3import os
4import socket
5import sys
6import uuid
7from http import HTTPStatus
8from urllib.error import HTTPError, URLError
9from urllib.parse import urlencode
10from urllib.request import urlopen, Request
12from pyngrok import process, conf, installer
13from pyngrok.exception import PyngrokNgrokHTTPError, PyngrokNgrokURLError, PyngrokSecurityError, PyngrokError
15__author__ = "Alex Laird"
16__copyright__ = "Copyright 2023, Alex Laird"
17__version__ = "6.1.1"
19from pyngrok.installer import get_default_config
21logger = logging.getLogger(__name__)
23_current_tunnels = {}
26class NgrokTunnel:
27 """
28 An object containing information about a ``ngrok`` tunnel.
30 :var data: The original tunnel data.
31 :vartype data: dict
32 :var name: The name of the tunnel.
33 :vartype name: str
34 :var proto: The protocol of the tunnel.
35 :vartype proto: str
36 :var uri: The tunnel URI, a relative path that can be used to make requests to the ``ngrok`` web interface.
37 :vartype uri: str
38 :var public_url: The public ``ngrok`` URL.
39 :vartype public_url: str
40 :var config: The config for the tunnel.
41 :vartype config: dict
42 :var metrics: Metrics for `the tunnel <https://ngrok.com/docs/ngrok-agent/api#list-tunnels>`_.
43 :vartype metrics: dict
44 :var pyngrok_config: The ``pyngrok`` configuration to use when interacting with the ``ngrok``.
45 :vartype pyngrok_config: PyngrokConfig
46 :var api_url: The API URL for the ``ngrok`` web interface.
47 :vartype api_url: str
48 """
50 def __init__(self, data, pyngrok_config, api_url):
51 self.data = data
53 self.id = data.get("ID", None)
54 self.name = data.get("name")
55 self.proto = data.get("proto")
56 self.uri = data.get("uri")
57 self.public_url = data.get("public_url")
58 self.config = data.get("config", {})
59 self.metrics = data.get("metrics", {})
61 self.pyngrok_config = pyngrok_config
62 self.api_url = api_url
64 def __repr__(self):
65 return "<NgrokTunnel: \"{}\" -> \"{}\">".format(self.public_url, self.config["addr"]) if self.config.get(
66 "addr", None) else "<pending Tunnel>"
68 def __str__(self): # pragma: no cover
69 return "NgrokTunnel: \"{}\" -> \"{}\"".format(self.public_url, self.config["addr"]) if self.config.get(
70 "addr", None) else "<pending Tunnel>"
72 def refresh_metrics(self):
73 """
74 Get the latest metrics for the tunnel and update the ``metrics`` variable.
75 """
76 logger.info("Refreshing metrics for tunnel: {}".format(self.public_url))
78 data = api_request("{}{}".format(self.api_url, self.uri), method="GET",
79 timeout=self.pyngrok_config.request_timeout)
81 if "metrics" not in data:
82 raise PyngrokError("The ngrok API did not return \"metrics\" in the response")
84 self.data["metrics"] = data["metrics"]
85 self.metrics = self.data["metrics"]
88def install_ngrok(pyngrok_config=None):
89 """
90 Download, install, and initialize ``ngrok`` for the given config. If ``ngrok`` and its default
91 config is already installed, calling this method will do nothing.
93 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
94 overriding :func:`~pyngrok.conf.get_default()`.
95 :type pyngrok_config: PyngrokConfig, optional
96 """
97 if pyngrok_config is None:
98 pyngrok_config = conf.get_default()
100 if not os.path.exists(pyngrok_config.ngrok_path):
101 installer.install_ngrok(pyngrok_config.ngrok_path, pyngrok_config.ngrok_version)
103 config_path = conf.get_config_path(pyngrok_config)
105 # Install the config to the requested path
106 if not os.path.exists(config_path):
107 installer.install_default_config(config_path, ngrok_version=pyngrok_config.ngrok_version)
109 # Install the default config, even if we don't need it this time, if it doesn't already exist
110 if conf.DEFAULT_NGROK_CONFIG_PATH != config_path and \
111 not os.path.exists(conf.DEFAULT_NGROK_CONFIG_PATH):
112 installer.install_default_config(conf.DEFAULT_NGROK_CONFIG_PATH, ngrok_version=pyngrok_config.ngrok_version)
115def set_auth_token(token, pyngrok_config=None):
116 """
117 Set the ``ngrok`` auth token in the config file, enabling authenticated features (for instance,
118 more concurrent tunnels, custom subdomains, etc.).
120 If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method
121 will first download and install ``ngrok``.
123 :param token: The auth token to set.
124 :type token: str
125 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
126 overriding :func:`~pyngrok.conf.get_default()`.
127 :type pyngrok_config: PyngrokConfig, optional
128 """
129 if pyngrok_config is None:
130 pyngrok_config = conf.get_default()
132 install_ngrok(pyngrok_config)
134 process.set_auth_token(pyngrok_config, token)
137def get_ngrok_process(pyngrok_config=None):
138 """
139 Get the current ``ngrok`` process for the given config's ``ngrok_path``.
141 If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method
142 will first download and install ``ngrok``.
144 If ``ngrok`` is not running, calling this method will first start a process with
145 :class:`~pyngrok.conf.PyngrokConfig`.
147 Use :func:`~pyngrok.process.is_process_running` to check if a process is running without also implicitly
148 installing and starting it.
150 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
151 overriding :func:`~pyngrok.conf.get_default()`.
152 :type pyngrok_config: PyngrokConfig, optional
153 :return: The ``ngrok`` process.
154 :rtype: NgrokProcess
155 """
156 if pyngrok_config is None:
157 pyngrok_config = conf.get_default()
159 install_ngrok(pyngrok_config)
161 return process.get_process(pyngrok_config)
164def _apply_cloud_edge_to_tunnel(tunnel, pyngrok_config):
165 if not tunnel.public_url and pyngrok_config.api_key and tunnel.id:
166 tunnel_response = api_request("https://api.ngrok.com/tunnels/{}".format(tunnel.id), method="GET",
167 auth=pyngrok_config.api_key)
168 if "labels" not in tunnel_response or "edge" not in tunnel_response["labels"]:
169 raise PyngrokError(
170 "Tunnel {} does not have \"labels\", use a Tunnel configured on Cloud Edge.".format(tunnel.data["ID"]))
172 edge = tunnel_response["labels"]["edge"]
173 if edge.startswith("edghts_"):
174 edges_prefix = "https"
175 elif edge.startswith("edgtcp"):
176 edges_prefix = "tcp"
177 elif edge.startswith("edgtls"):
178 edges_prefix = "tls"
179 else:
180 raise PyngrokError("Unknown Edge prefix: {}.".format(edge))
182 edge_response = api_request("https://api.ngrok.com/edges/{}/{}".format(edges_prefix, edge), method="GET",
183 auth=pyngrok_config.api_key)
185 if "hostports" not in edge_response or len(edge_response["hostports"]) < 1:
186 raise PyngrokError(
187 "No Endpoint is attached to your Cloud Edge {}, login to the ngrok dashboard to attach an Endpoint to your Edge first.".format(
188 edge))
190 tunnel.public_url = "{}://{}".format(edges_prefix, edge_response["hostports"][0])
191 tunnel.proto = edges_prefix
194def connect(addr=None, proto=None, name=None, pyngrok_config=None, **options):
195 """
196 Establish a new ``ngrok`` tunnel for the given protocol to the given port, returning an object representing
197 the connected tunnel.
199 If a `tunnel definition in ngrok's config file
200 <https://ngrok.com/docs/secure-tunnels/ngrok-agent/reference/config/#tunnel-definitions>`_ matches the given
201 ``name``, it will be loaded and used to start the tunnel. When ``name`` is ``None`` and a "pyngrok-default" tunnel
202 definition exists in ``ngrok``'s config, it will be loaded and use. Any ``kwargs`` passed as ``options`` will
203 override properties from the loaded tunnel definition.
205 If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method
206 will first download and install ``ngrok``.
208 ``pyngrok`` is compatible with ``ngrok`` v2 and v3, but by default it will install v3. To install v2 instead,
209 set ``ngrok_version`` in :class:`~pyngrok.conf.PyngrokConfig`:
211 If ``ngrok`` is not running, calling this method will first start a process with
212 :class:`~pyngrok.conf.PyngrokConfig`.
214 .. note::
216 ``ngrok`` v2's default behavior for ``http`` when no additional properties are passed is to open *two* tunnels,
217 one ``http`` and one ``https``. This method will return a reference to the ``http`` tunnel in this case. If
218 only a single tunnel is needed, pass ``bind_tls=True`` and a reference to the ``https`` tunnel will be returned.
220 :param addr: The local port to which the tunnel will forward traffic, or a
221 `local directory or network address <https://ngrok.com/docs/secure-tunnels/tunnels/http-tunnels#file-url>`_, defaults to "80".
222 :type addr: str, optional
223 :param proto: A valid `tunnel protocol
224 <https://ngrok.com/docs/secure-tunnels/ngrok-agent/reference/config/#tunnel-definitions>`_, defaults to "http".
225 :type proto: str, optional
226 :param name: A friendly name for the tunnel, or the name of a `ngrok tunnel definition <https://ngrok.com/docs/secure-tunnels/ngrok-agent/reference/config/#tunnel-definitions>`_
227 to be used.
228 :type name: str, optional
229 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
230 overriding :func:`~pyngrok.conf.get_default()`.
231 :type pyngrok_config: PyngrokConfig, optional
232 :param options: Remaining ``kwargs`` are passed as `configuration for the ngrok
233 tunnel <https://ngrok.com/docs/secure-tunnels/ngrok-agent/reference/config/#tunnel-definitions>`_.
234 :type options: dict, optional
235 :return: The created ``ngrok`` tunnel.
236 :rtype: NgrokTunnel
237 """
238 if "labels" in options:
239 raise PyngrokError("\"labels\" cannot be passed to connect(), define a tunnel definition in the config file.")
241 if pyngrok_config is None:
242 pyngrok_config = conf.get_default()
244 config_path = conf.get_config_path(pyngrok_config)
246 if os.path.exists(config_path):
247 config = installer.get_ngrok_config(config_path)
248 else:
249 config = get_default_config(pyngrok_config.ngrok_version)
251 tunnel_definitions = config.get("tunnels", {})
252 # If a "pyngrok-default" tunnel definition exists in the ngrok config, use that
253 if not name and "pyngrok-default" in tunnel_definitions:
254 name = "pyngrok-default"
256 # Use a tunnel definition for the given name, if it exists
257 if name and name in tunnel_definitions:
258 tunnel_definition = tunnel_definitions[name]
260 if "labels" in tunnel_definition and "bind_tls" in options:
261 raise PyngrokError("\"bind_tls\" cannot be set when \"labels\" is also on the tunnel definition.")
263 addr = tunnel_definition.get("addr") if not addr else addr
264 proto = tunnel_definition.get("proto") if not proto else proto
265 # Use the tunnel definition as the base, but override with any passed in options
266 tunnel_definition.update(options)
267 options = tunnel_definition
269 if "labels" in options and not pyngrok_config.api_key:
270 raise PyngrokError(
271 "\"PyngrokConfig.api_key\" must be set when \"labels\" is on the tunnel definition.")
273 addr = str(addr) if addr else "80"
274 # Only apply a default proto label if "labels" isn't defined
275 if not proto and "labels" not in options:
276 proto = "http"
278 if not name:
279 if not addr.startswith("file://"):
280 name = "{}-{}-{}".format(proto, addr, uuid.uuid4())
281 else:
282 name = "{}-file-{}".format(proto, uuid.uuid4())
284 logger.info("Opening tunnel named: {}".format(name))
286 config = {
287 "name": name,
288 "addr": addr
289 }
290 options.update(config)
292 # Only apply proto when "labels" is not defined
293 if "labels" not in options:
294 options["proto"] = proto
296 # Upgrade legacy parameters, if present
297 if pyngrok_config.ngrok_version == "v3":
298 if "bind_tls" in options:
299 if options.get("bind_tls") is True or options.get("bind_tls") == "true":
300 options["schemes"] = ["https"]
301 elif not options.get("bind_tls") is not False or options.get("bind_tls") == "false":
302 options["schemes"] = ["http"]
303 else:
304 options["schemes"] = ["http", "https"]
306 options.pop("bind_tls")
308 if "auth" in options:
309 auth = options.get("auth")
310 if isinstance(auth, list):
311 options["basic_auth"] = auth
312 else:
313 options["basic_auth"] = [auth]
315 options.pop("auth")
317 api_url = get_ngrok_process(pyngrok_config).api_url
319 logger.debug("Creating tunnel with options: {}".format(options))
321 tunnel = NgrokTunnel(api_request("{}/api/tunnels".format(api_url), method="POST", data=options,
322 timeout=pyngrok_config.request_timeout),
323 pyngrok_config, api_url)
325 if pyngrok_config.ngrok_version == "v2" and proto == "http" and options.get("bind_tls", "both") == "both":
326 tunnel = NgrokTunnel(api_request("{}{}%20%28http%29".format(api_url, tunnel.uri), method="GET",
327 timeout=pyngrok_config.request_timeout),
328 pyngrok_config, api_url)
330 _apply_cloud_edge_to_tunnel(tunnel, pyngrok_config)
332 _current_tunnels[tunnel.public_url] = tunnel
334 return tunnel
337def disconnect(public_url, pyngrok_config=None):
338 """
339 Disconnect the ``ngrok`` tunnel for the given URL, if open.
341 :param public_url: The public URL of the tunnel to disconnect.
342 :type public_url: str
343 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
344 overriding :func:`~pyngrok.conf.get_default()`.
345 :type pyngrok_config: PyngrokConfig, optional
346 """
347 if pyngrok_config is None:
348 pyngrok_config = conf.get_default()
350 # If ngrok is not running, there are no tunnels to disconnect
351 if not process.is_process_running(pyngrok_config.ngrok_path):
352 return
354 api_url = get_ngrok_process(pyngrok_config).api_url
356 if public_url not in _current_tunnels:
357 get_tunnels(pyngrok_config)
359 # One more check, if the given URL is still not in the list of tunnels, it is not active
360 if public_url not in _current_tunnels:
361 return
363 tunnel = _current_tunnels[public_url]
365 logger.info("Disconnecting tunnel: {}".format(tunnel.public_url))
367 api_request("{}{}".format(api_url, tunnel.uri), method="DELETE",
368 timeout=pyngrok_config.request_timeout)
370 _current_tunnels.pop(public_url, None)
373def get_tunnels(pyngrok_config=None):
374 """
375 Get a list of active ``ngrok`` tunnels for the given config's ``ngrok_path``.
377 If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method
378 will first download and install ``ngrok``.
380 If ``ngrok`` is not running, calling this method will first start a process with
381 :class:`~pyngrok.conf.PyngrokConfig`.
383 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
384 overriding :func:`~pyngrok.conf.get_default()`.
385 :type pyngrok_config: PyngrokConfig, optional
386 :return: The active ``ngrok`` tunnels.
387 :rtype: list[NgrokTunnel]
388 """
389 if pyngrok_config is None:
390 pyngrok_config = conf.get_default()
392 api_url = get_ngrok_process(pyngrok_config).api_url
394 _current_tunnels.clear()
395 for tunnel in api_request("{}/api/tunnels".format(api_url), method="GET",
396 timeout=pyngrok_config.request_timeout)["tunnels"]:
397 ngrok_tunnel = NgrokTunnel(tunnel, pyngrok_config, api_url)
398 _apply_cloud_edge_to_tunnel(ngrok_tunnel, pyngrok_config)
399 _current_tunnels[ngrok_tunnel.public_url] = ngrok_tunnel
401 return list(_current_tunnels.values())
404def kill(pyngrok_config=None):
405 """
406 Terminate the ``ngrok`` processes, if running, for the given config's ``ngrok_path``. This method will not
407 block, it will just issue a kill request.
409 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
410 overriding :func:`~pyngrok.conf.get_default()`.
411 :type pyngrok_config: PyngrokConfig, optional
412 """
413 if pyngrok_config is None:
414 pyngrok_config = conf.get_default()
416 process.kill_process(pyngrok_config.ngrok_path)
418 _current_tunnels.clear()
421def get_version(pyngrok_config=None):
422 """
423 Get a tuple with the ``ngrok`` and ``pyngrok`` versions.
425 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
426 overriding :func:`~pyngrok.conf.get_default()`.
427 :type pyngrok_config: PyngrokConfig, optional
428 :return: A tuple of ``(ngrok_version, pyngrok_version)``.
429 :rtype: tuple
430 """
431 if pyngrok_config is None:
432 pyngrok_config = conf.get_default()
434 ngrok_version = process.capture_run_process(pyngrok_config.ngrok_path, ["--version"]).split("version ")[1]
436 return ngrok_version, __version__
439def update(pyngrok_config=None):
440 """
441 Update ``ngrok`` for the given config's ``ngrok_path``, if an update is available.
443 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
444 overriding :func:`~pyngrok.conf.get_default()`.
445 :type pyngrok_config: PyngrokConfig, optional
446 :return: The result from the ``ngrok`` update.
447 :rtype: str
448 """
449 if pyngrok_config is None:
450 pyngrok_config = conf.get_default()
452 return process.capture_run_process(pyngrok_config.ngrok_path, ["update"])
455def api_request(url, method="GET", data=None, params=None, timeout=4, auth=None):
456 """
457 Invoke an API request to the given URL, returning JSON data from the response.
459 One use for this method is making requests to ``ngrok`` tunnels:
461 .. code-block:: python
463 from pyngrok import ngrok
465 public_url = ngrok.connect()
466 response = ngrok.api_request("{}/some-route".format(public_url),
467 method="POST", data={"foo": "bar"})
469 Another is making requests to the ``ngrok`` API itself:
471 .. code-block:: python
473 from pyngrok import ngrok
475 api_url = ngrok.get_ngrok_process().api_url
476 response = ngrok.api_request("{}/api/requests/http".format(api_url),
477 params={"tunnel_name": "foo"})
479 :param url: The request URL.
480 :type url: str
481 :param method: The HTTP method.
482 :type method: str, optional
483 :param data: The request body.
484 :type data: dict, optional
485 :param params: The URL parameters.
486 :type params: dict, optional
487 :param timeout: The request timeout, in seconds.
488 :type timeout: float, optional
489 :param auth: Set as Bearer for an Authorization header.
490 :type auth: str, optional
491 :return: The response from the request.
492 :rtype: dict
493 """
494 if params is None:
495 params = {}
497 if not url.lower().startswith("http"):
498 raise PyngrokSecurityError("URL must start with \"http\": {}".format(url))
500 encoded_data = json.dumps(data).encode("utf-8") if data else None
502 if params:
503 url += "?{}".format(urlencode([(x, params[x]) for x in params]))
505 request = Request(url, method=method.upper())
506 request.add_header("Content-Type", "application/json")
507 if auth:
508 request.add_header("Ngrok-Version", "2")
509 request.add_header("Authorization", "Bearer {}".format(auth))
511 logger.debug("Making {} request to {} with data: {}".format(method, url, encoded_data))
513 try:
514 response = urlopen(request, encoded_data, timeout)
515 response_data = response.read().decode("utf-8")
517 status_code = response.getcode()
518 logger.debug("Response {}: {}".format(status_code, response_data.strip()))
520 if str(status_code)[0] != "2":
521 raise PyngrokNgrokHTTPError("ngrok client API returned {}: {}".format(status_code, response_data), url,
522 status_code, None, request.headers, response_data)
523 elif status_code == HTTPStatus.NO_CONTENT:
524 return {}
526 return json.loads(response_data)
527 except socket.timeout:
528 raise PyngrokNgrokURLError("ngrok client exception, URLError: timed out", "timed out")
529 except HTTPError as e:
530 response_data = e.read().decode("utf-8")
532 status_code = e.getcode()
533 logger.debug("Response {}: {}".format(status_code, response_data.strip()))
535 raise PyngrokNgrokHTTPError("ngrok client exception, API returned {}: {}".format(status_code, response_data),
536 e.url,
537 status_code, e.reason, e.headers, response_data)
538 except URLError as e:
539 raise PyngrokNgrokURLError("ngrok client exception, URLError: {}".format(e.reason), e.reason)
542def run(args=None, pyngrok_config=None):
543 """
544 Ensure ``ngrok`` is installed at the default path, then call :func:`~pyngrok.process.run_process`.
546 This method is meant for interacting with ``ngrok`` from the command line and is not necessarily
547 compatible with non-blocking API methods. For that, use :mod:`~pyngrok.ngrok`'s interface methods (like
548 :func:`~pyngrok.ngrok.connect`), or use :func:`~pyngrok.process.get_process`.
550 :param args: Arguments to be passed to the ``ngrok`` process.
551 :type args: list[str], optional
552 :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary,
553 overriding :func:`~pyngrok.conf.get_default()`.
554 :type pyngrok_config: PyngrokConfig, optional
555 """
556 if args is None:
557 args = []
558 if pyngrok_config is None:
559 pyngrok_config = conf.get_default()
561 install_ngrok(pyngrok_config)
563 process.run_process(pyngrok_config.ngrok_path, args)
566def main():
567 """
568 Entry point for the package's ``console_scripts``. This initializes a call from the command
569 line and invokes :func:`~pyngrok.ngrok.run`.
571 This method is meant for interacting with ``ngrok`` from the command line and is not necessarily
572 compatible with non-blocking API methods. For that, use :mod:`~pyngrok.ngrok`'s interface methods (like
573 :func:`~pyngrok.ngrok.connect`), or use :func:`~pyngrok.process.get_process`.
574 """
575 run(sys.argv[1:])
577 if len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1].lstrip("-").lstrip("-") == "help":
578 print("\nPYNGROK VERSION:\n {}".format(__version__))
579 elif len(sys.argv) == 2 and sys.argv[1].lstrip("-").lstrip("-") in ["v", "version"]:
580 print("pyngrok version {}".format(__version__))
583if __name__ == "__main__":
584 main()