uppercut-loopback-api 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ uv.lock
9
+ .env*
10
+ *.pem
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-loopback-api
3
+ Version: 1.0.0
4
+ Summary: A small JSON API on 127.0.0.1 for a private app behind Tailscale Serve or another reverse proxy: Host allowlist, strict bodies, redacted logs, exclusive port bind.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-loopback-api
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: dns-rebinding,http,json-api,loopback,pwa,reverse-proxy,tailscale
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # uppercut-loopback-api
27
+
28
+ A small JSON API server for a private app that runs on one machine and is reached through a reverse proxy, such as Tailscale Serve, from phones and other computers. It binds 127.0.0.1 only and owns its port alone, refuses Host headers it doesn't know, reads request bodies strictly, answers every error as JSON, and keeps secrets out of its request log. It can also serve a single-page web client with a web manifest and generated icons, so the app installs as a PWA. Standard library only, Python 3.9 or later.
29
+
30
+ ```sh
31
+ pip install uppercut-loopback-api
32
+ ```
33
+
34
+ ```python
35
+ from pathlib import Path
36
+ from uppercut_loopback_api import ApiError, LoopbackApp, health_route, serve, tailnet_hosts
37
+
38
+ APP = LoopbackApp(
39
+ name="Notes Remote",
40
+ short_name="NTS", # drawn on the icons in a 5x7 pixel font
41
+ mount="/notes", # the path the proxy publishes the app under
42
+ port=8890,
43
+ allowed_hosts=tailnet_hosts("tailnet.example", "studio"),
44
+ index_html=Path("web/index.html"),
45
+ log_path=Path("notes-remote.log"),
46
+ )
47
+
48
+ NOTES = {"a": "first note"}
49
+
50
+
51
+ def get_note(handler, _body):
52
+ note_id = handler.query().get("id", "")
53
+ if note_id not in NOTES:
54
+ raise ApiError(404, "no such note")
55
+ return 200, {"id": note_id, "text": NOTES[note_id]}
56
+
57
+
58
+ def put_note(_handler, body):
59
+ if not isinstance(body.get("id"), str) or not isinstance(body.get("text"), str):
60
+ raise ApiError(400, 'body must be {"id": str, "text": str}')
61
+ NOTES[body["id"]] = body["text"]
62
+ return 200, {"saved": True}
63
+
64
+
65
+ ROUTES = {
66
+ ("GET", "/api/health"): health_route(lambda: {"notes": len(NOTES)}, app="notes"),
67
+ ("GET", "/api/note"): get_note,
68
+ ("PUT", "/api/note"): put_note,
69
+ }
70
+
71
+ if __name__ == "__main__":
72
+ serve(APP, ROUTES)
73
+ ```
74
+
75
+ Then publish it to your tailnet, for example with `tailscale serve --bg --set-path=/notes http://127.0.0.1:8890/notes`.
76
+
77
+ ## What it does for every request
78
+
79
+ - **Host check.** Only the names in `allowed_hosts`, plus `127.0.0.1` and `localhost`, are answered; anything else, a missing Host or two Host headers get `403`. This stops a web page from reaching the loopback port through DNS rebinding.
80
+ - **Mount.** Routes work under the mount (`/notes/api/note`) and without it (`/api/note`), so a dedicated hostname can proxy to the root. A bare `/notes` redirects to `/notes/`. Use `mount=""` for an app at the root.
81
+ - **Strict bodies.** `PUT` and `POST` need exactly one decimal `Content-Length` within `max_body_bytes`, no `Transfer-Encoding`, and a JSON object. Anything else is `400` (or `413` when too long) before your route runs.
82
+ - **JSON errors.** Raise `ApiError(status, message, **extra)` for `{"error": message, **extra}`. An `OSError` becomes `500` with its reason; any other exception becomes `500 {"error": "internal error"}` and only its type is logged.
83
+ - **Headers.** Every response has `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`; the web client also gets a Content-Security-Policy (`index_csp`).
84
+ - **Request log.** One line per request: client address, method, the mount plus a known path (or `<unknown>`), and the status. Query strings, bodies, headers, unknown paths and parser error text are never written.
85
+ - **Exclusive port.** On Windows the stdlib server sets `SO_REUSEADDR`, which lets a second copy bind the same port without an error and take some of the first one's requests. `LoopbackServer` sets `SO_EXCLUSIVEADDRUSE` instead, so a second copy fails to start.
86
+
87
+ ## API
88
+
89
+ | Name | What it is |
90
+ | --- | --- |
91
+ | `LoopbackApp(name, port, allowed_hosts=(), mount="", short_name="", web_client=True, index_html=None, index_csp=..., background=(17, 19, 24), accent=(110, 231, 183), log_path=None, log=None, max_body_bytes=65536, gzip_min_bytes=None, server_version="loopback-api")` | One app's configuration. `index_html` is a path or bytes; a missing file serves a placeholder. `log` is a callable that gets each log line, for example a `logging` method. `gzip_min_bytes` turns on gzip for JSON responses at least that long when the client accepts it. |
92
+ | `tailnet_hosts(tailnet, *names)` | `{name, name.tailnet}` for each name, for `allowed_hosts` |
93
+ | `serve(app, routes, port=None)` | Bind 127.0.0.1 and serve until stopped |
94
+ | `make_server(app, routes, port=None)` | The bound `LoopbackServer`, not yet serving (port `0` picks a free one; useful in tests) |
95
+ | `make_handler(app, routes)` | The request handler class |
96
+ | `health_route(check=None, **fields)` | A route answering `{"ok": true, **fields, **check()}` |
97
+ | `require_bearer(token, route)` | Wraps a route so it answers `401` unless `Authorization: Bearer <token>` matches (constant-time compare) |
98
+ | `ApiError(status, message, **extra)` | Raise from a route for a JSON error |
99
+ | `log_line(app, line)` | Write a line to the app's log yourself; never pass secrets |
100
+ | `pixel_mark_png(text, size, background, foreground)` | A square PNG with up to four letters or digits in the pixel font |
101
+ | `LoopbackServer`, `LoopbackHandler`, `host_name`, `manifest_of`, `GLYPHS`, `LOOPBACK` | The pieces the above are built from |
102
+
103
+ Routes are a dict keyed by `(method, path)`, where the method is `GET`, `PUT`, `POST` or `DELETE` and the path is below the mount. A route is called as `route(handler, body)`, where `body` is the parsed JSON object for `PUT` and `POST` and `None` otherwise, and returns `(status, payload)` with a JSON-serializable payload. The handler gives routes `handler.query()` (first value of each query parameter) and `handler.headers`.
104
+
105
+ ## License
106
+
107
+ MIT
@@ -0,0 +1,82 @@
1
+ # uppercut-loopback-api
2
+
3
+ A small JSON API server for a private app that runs on one machine and is reached through a reverse proxy, such as Tailscale Serve, from phones and other computers. It binds 127.0.0.1 only and owns its port alone, refuses Host headers it doesn't know, reads request bodies strictly, answers every error as JSON, and keeps secrets out of its request log. It can also serve a single-page web client with a web manifest and generated icons, so the app installs as a PWA. Standard library only, Python 3.9 or later.
4
+
5
+ ```sh
6
+ pip install uppercut-loopback-api
7
+ ```
8
+
9
+ ```python
10
+ from pathlib import Path
11
+ from uppercut_loopback_api import ApiError, LoopbackApp, health_route, serve, tailnet_hosts
12
+
13
+ APP = LoopbackApp(
14
+ name="Notes Remote",
15
+ short_name="NTS", # drawn on the icons in a 5x7 pixel font
16
+ mount="/notes", # the path the proxy publishes the app under
17
+ port=8890,
18
+ allowed_hosts=tailnet_hosts("tailnet.example", "studio"),
19
+ index_html=Path("web/index.html"),
20
+ log_path=Path("notes-remote.log"),
21
+ )
22
+
23
+ NOTES = {"a": "first note"}
24
+
25
+
26
+ def get_note(handler, _body):
27
+ note_id = handler.query().get("id", "")
28
+ if note_id not in NOTES:
29
+ raise ApiError(404, "no such note")
30
+ return 200, {"id": note_id, "text": NOTES[note_id]}
31
+
32
+
33
+ def put_note(_handler, body):
34
+ if not isinstance(body.get("id"), str) or not isinstance(body.get("text"), str):
35
+ raise ApiError(400, 'body must be {"id": str, "text": str}')
36
+ NOTES[body["id"]] = body["text"]
37
+ return 200, {"saved": True}
38
+
39
+
40
+ ROUTES = {
41
+ ("GET", "/api/health"): health_route(lambda: {"notes": len(NOTES)}, app="notes"),
42
+ ("GET", "/api/note"): get_note,
43
+ ("PUT", "/api/note"): put_note,
44
+ }
45
+
46
+ if __name__ == "__main__":
47
+ serve(APP, ROUTES)
48
+ ```
49
+
50
+ Then publish it to your tailnet, for example with `tailscale serve --bg --set-path=/notes http://127.0.0.1:8890/notes`.
51
+
52
+ ## What it does for every request
53
+
54
+ - **Host check.** Only the names in `allowed_hosts`, plus `127.0.0.1` and `localhost`, are answered; anything else, a missing Host or two Host headers get `403`. This stops a web page from reaching the loopback port through DNS rebinding.
55
+ - **Mount.** Routes work under the mount (`/notes/api/note`) and without it (`/api/note`), so a dedicated hostname can proxy to the root. A bare `/notes` redirects to `/notes/`. Use `mount=""` for an app at the root.
56
+ - **Strict bodies.** `PUT` and `POST` need exactly one decimal `Content-Length` within `max_body_bytes`, no `Transfer-Encoding`, and a JSON object. Anything else is `400` (or `413` when too long) before your route runs.
57
+ - **JSON errors.** Raise `ApiError(status, message, **extra)` for `{"error": message, **extra}`. An `OSError` becomes `500` with its reason; any other exception becomes `500 {"error": "internal error"}` and only its type is logged.
58
+ - **Headers.** Every response has `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`; the web client also gets a Content-Security-Policy (`index_csp`).
59
+ - **Request log.** One line per request: client address, method, the mount plus a known path (or `<unknown>`), and the status. Query strings, bodies, headers, unknown paths and parser error text are never written.
60
+ - **Exclusive port.** On Windows the stdlib server sets `SO_REUSEADDR`, which lets a second copy bind the same port without an error and take some of the first one's requests. `LoopbackServer` sets `SO_EXCLUSIVEADDRUSE` instead, so a second copy fails to start.
61
+
62
+ ## API
63
+
64
+ | Name | What it is |
65
+ | --- | --- |
66
+ | `LoopbackApp(name, port, allowed_hosts=(), mount="", short_name="", web_client=True, index_html=None, index_csp=..., background=(17, 19, 24), accent=(110, 231, 183), log_path=None, log=None, max_body_bytes=65536, gzip_min_bytes=None, server_version="loopback-api")` | One app's configuration. `index_html` is a path or bytes; a missing file serves a placeholder. `log` is a callable that gets each log line, for example a `logging` method. `gzip_min_bytes` turns on gzip for JSON responses at least that long when the client accepts it. |
67
+ | `tailnet_hosts(tailnet, *names)` | `{name, name.tailnet}` for each name, for `allowed_hosts` |
68
+ | `serve(app, routes, port=None)` | Bind 127.0.0.1 and serve until stopped |
69
+ | `make_server(app, routes, port=None)` | The bound `LoopbackServer`, not yet serving (port `0` picks a free one; useful in tests) |
70
+ | `make_handler(app, routes)` | The request handler class |
71
+ | `health_route(check=None, **fields)` | A route answering `{"ok": true, **fields, **check()}` |
72
+ | `require_bearer(token, route)` | Wraps a route so it answers `401` unless `Authorization: Bearer <token>` matches (constant-time compare) |
73
+ | `ApiError(status, message, **extra)` | Raise from a route for a JSON error |
74
+ | `log_line(app, line)` | Write a line to the app's log yourself; never pass secrets |
75
+ | `pixel_mark_png(text, size, background, foreground)` | A square PNG with up to four letters or digits in the pixel font |
76
+ | `LoopbackServer`, `LoopbackHandler`, `host_name`, `manifest_of`, `GLYPHS`, `LOOPBACK` | The pieces the above are built from |
77
+
78
+ Routes are a dict keyed by `(method, path)`, where the method is `GET`, `PUT`, `POST` or `DELETE` and the path is below the mount. A route is called as `route(handler, body)`, where `body` is the parsed JSON object for `PUT` and `POST` and `None` otherwise, and returns `(status, payload)` with a JSON-serializable payload. The handler gives routes `handler.query()` (first value of each query parameter) and `handler.headers`.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-loopback-api"
7
+ version = "1.0.0"
8
+ description = "A small JSON API on 127.0.0.1 for a private app behind Tailscale Serve or another reverse proxy: Host allowlist, strict bodies, redacted logs, exclusive port bind."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ keywords = ["http", "loopback", "tailscale", "reverse-proxy", "json-api", "pwa", "dns-rebinding"]
14
+ dependencies = []
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: MacOS",
19
+ "Operating System :: Microsoft :: Windows",
20
+ "Operating System :: POSIX",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
29
+ "Typing :: Typed",
30
+ ]
31
+
32
+ [project.urls]
33
+ Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-loopback-api"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/uppercut_loopback_api"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,43 @@
1
+ """A small JSON API on 127.0.0.1 for a private app that a reverse proxy such as Tailscale Serve publishes."""
2
+
3
+ from ._icon import GLYPHS, pixel_mark_png
4
+ from ._server import (
5
+ LOOPBACK,
6
+ ApiError,
7
+ LoopbackApp,
8
+ LoopbackHandler,
9
+ LoopbackServer,
10
+ Route,
11
+ Routes,
12
+ health_route,
13
+ host_name,
14
+ log_line,
15
+ make_handler,
16
+ make_server,
17
+ manifest_of,
18
+ require_bearer,
19
+ serve,
20
+ tailnet_hosts,
21
+ )
22
+
23
+ __all__ = [
24
+ "GLYPHS",
25
+ "LOOPBACK",
26
+ "ApiError",
27
+ "LoopbackApp",
28
+ "LoopbackHandler",
29
+ "LoopbackServer",
30
+ "Route",
31
+ "Routes",
32
+ "health_route",
33
+ "host_name",
34
+ "log_line",
35
+ "make_handler",
36
+ "make_server",
37
+ "manifest_of",
38
+ "pixel_mark_png",
39
+ "require_bearer",
40
+ "serve",
41
+ "tailnet_hosts",
42
+ ]
43
+ __version__ = "1.0.0"
@@ -0,0 +1,61 @@
1
+ """The pixel mark: up to four letters or digits in a 5x7 pixel font, written as a PNG."""
2
+
3
+ import struct
4
+ import zlib
5
+ from typing import Sequence
6
+
7
+ # Each glyph is seven rows of five pixels, top to bottom.
8
+ GLYPHS = {
9
+ "A": "01110 10001 10001 11111 10001 10001 10001", "B": "11110 10001 10001 11110 10001 10001 11110",
10
+ "C": "01111 10000 10000 10000 10000 10000 01111", "D": "11110 10001 10001 10001 10001 10001 11110",
11
+ "E": "11111 10000 10000 11110 10000 10000 11111", "F": "11111 10000 10000 11110 10000 10000 10000",
12
+ "G": "01111 10000 10000 10011 10001 10001 01111", "H": "10001 10001 10001 11111 10001 10001 10001",
13
+ "I": "11111 00100 00100 00100 00100 00100 11111", "J": "00111 00010 00010 00010 00010 10010 01100",
14
+ "K": "10001 10010 10100 11000 10100 10010 10001", "L": "10000 10000 10000 10000 10000 10000 11111",
15
+ "M": "10001 11011 10101 10101 10001 10001 10001", "N": "10001 11001 10101 10011 10001 10001 10001",
16
+ "O": "01110 10001 10001 10001 10001 10001 01110", "P": "11110 10001 10001 11110 10000 10000 10000",
17
+ "Q": "01110 10001 10001 10001 10101 10010 01101", "R": "11110 10001 10001 11110 10100 10010 10001",
18
+ "S": "01111 10000 10000 01110 00001 00001 11110", "T": "11111 00100 00100 00100 00100 00100 00100",
19
+ "U": "10001 10001 10001 10001 10001 10001 01110", "V": "10001 10001 10001 10001 01010 01010 00100",
20
+ "W": "10001 10001 10001 10101 10101 10101 01010", "X": "10001 10001 01010 00100 01010 10001 10001",
21
+ "Y": "10001 10001 01010 00100 00100 00100 00100", "Z": "11111 00001 00010 00100 01000 10000 11111",
22
+ "0": "01110 10001 10011 10101 11001 10001 01110", "1": "00100 01100 00100 00100 00100 00100 01110",
23
+ "2": "01110 10001 00001 00010 00100 01000 11111", "3": "11110 00001 00001 01110 00001 00001 11110",
24
+ "4": "00010 00110 01010 10010 11111 00010 00010", "5": "11111 10000 11110 00001 00001 10001 01110",
25
+ "6": "01110 10000 10000 11110 10001 10001 01110", "7": "11111 00001 00010 00100 01000 01000 01000",
26
+ "8": "01110 10001 10001 01110 10001 10001 01110", "9": "01110 10001 10001 01111 00001 00001 01110",
27
+ }
28
+
29
+
30
+ def pixel_mark_png(text: str, size: int, background: Sequence[int], foreground: Sequence[int]) -> bytes:
31
+ """A square RGB PNG, `size` pixels wide, with `text` centered in the 5x7 pixel font.
32
+
33
+ Only A-Z and 0-9 are drawn, at most four of them; lower case is raised. Text with none
34
+ of those characters gives a plain tile. No image library is needed.
35
+ """
36
+ text = "".join(ch for ch in text.upper() if ch in GLYPHS)[:4]
37
+ columns = max(1, len(text)) * 6 - 1
38
+ cell = max(1, size // (columns + 7))
39
+ ox, oy = (size - columns * cell) // 2, (size - 7 * cell) // 2
40
+ lit = set()
41
+ for i, ch in enumerate(text):
42
+ for r, row in enumerate(GLYPHS[ch].split()):
43
+ for c, bit in enumerate(row):
44
+ if bit == "1":
45
+ lit.add((i * 6 + c, r))
46
+ bg, fg = bytes(background), bytes(foreground)
47
+ rows = []
48
+ for y in range(size):
49
+ row = bytearray([0])
50
+ for x in range(size):
51
+ gx, gy = x - ox, y - oy
52
+ row += fg if gx >= 0 and gy >= 0 and (gx // cell, gy // cell) in lit else bg
53
+ rows.append(bytes(row))
54
+
55
+ def chunk(kind: bytes, body: bytes) -> bytes:
56
+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
57
+
58
+ return (b"\x89PNG\r\n\x1a\n"
59
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0))
60
+ + chunk(b"IDAT", zlib.compress(b"".join(rows), 9))
61
+ + chunk(b"IEND", b""))
@@ -0,0 +1,372 @@
1
+ """A small JSON API on 127.0.0.1 for a private app that a reverse proxy publishes."""
2
+
3
+ import gzip
4
+ import hmac
5
+ import json
6
+ import os
7
+ import socket
8
+ import sys
9
+ import threading
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
13
+ from pathlib import Path
14
+ from typing import Callable, Dict, FrozenSet, Iterable, Optional, Tuple, Union
15
+ from urllib.parse import parse_qs
16
+
17
+ from ._icon import pixel_mark_png
18
+
19
+ LOOPBACK = "127.0.0.1"
20
+ LOOPBACK_NAMES = frozenset({LOOPBACK, "localhost"})
21
+ METHODS = ("GET", "PUT", "POST", "DELETE")
22
+ STATIC_PATHS = ("/", "/manifest.webmanifest", "/icon-180.png", "/icon-512.png")
23
+ DEFAULT_INDEX_CSP = (
24
+ "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
25
+ "img-src 'self' data:; connect-src 'self'; manifest-src 'self'; frame-ancestors 'none'"
26
+ )
27
+
28
+
29
+ class ApiError(Exception):
30
+ """Raise from a route to answer with `{"error": message, **extra}` and `status`."""
31
+
32
+ def __init__(self, status: int, message: str, **extra: object) -> None:
33
+ super().__init__(message)
34
+ self.status = status
35
+ self.body = {"error": message, **extra}
36
+
37
+
38
+ def tailnet_hosts(tailnet: str, *names: str) -> FrozenSet[str]:
39
+ """Each name and `name.tailnet`, lower case: the Host headers a tailnet proxy sends.
40
+
41
+ `tailnet_hosts("tailnet.example", "studio", "notes")` accepts `studio`,
42
+ `studio.tailnet.example`, `notes` and `notes.tailnet.example`.
43
+ """
44
+ tailnet = tailnet.strip(".").lower()
45
+ hosts = set()
46
+ for name in names:
47
+ name = name.strip(".").lower()
48
+ hosts |= {name, f"{name}.{tailnet}"}
49
+ return frozenset(hosts)
50
+
51
+
52
+ @dataclass
53
+ class LoopbackApp:
54
+ """One app's configuration.
55
+
56
+ allowed_hosts: Host header names (without port) the app answers. 127.0.0.1 and
57
+ localhost are always accepted; every other Host gets 403, which stops DNS
58
+ rebinding from a web page reaching the loopback port.
59
+ mount: path prefix the proxy publishes the app under, such as "/notes", or "" for
60
+ the root. Requests work with or without it, and a bare "/notes" redirects to "/notes/".
61
+ web_client: serve index.html at "/", a web manifest and two pixel-mark icons.
62
+ log_path / log: where the request log goes (a file, a callable, both or neither).
63
+ Lines hold the method, a known path or "<unknown>", and the status; never query
64
+ strings, bodies, headers or unknown paths.
65
+ gzip_min_bytes: gzip JSON responses at least this long when the client accepts gzip.
66
+ """
67
+
68
+ name: str
69
+ port: int
70
+ allowed_hosts: Iterable[str] = ()
71
+ mount: str = ""
72
+ short_name: str = ""
73
+ web_client: bool = True
74
+ index_html: Union[Path, bytes, None] = None
75
+ index_csp: str = DEFAULT_INDEX_CSP
76
+ background: Tuple[int, int, int] = (17, 19, 24)
77
+ accent: Tuple[int, int, int] = (110, 231, 183)
78
+ log_path: Optional[Path] = None
79
+ log: Optional[Callable[[str], None]] = None
80
+ max_body_bytes: int = 64 * 1024
81
+ gzip_min_bytes: Optional[int] = None
82
+ server_version: str = "loopback-api"
83
+
84
+ def __post_init__(self) -> None:
85
+ mount = self.mount.strip()
86
+ if mount in ("", "/"):
87
+ mount = ""
88
+ else:
89
+ mount = "/" + mount.strip("/")
90
+ if "?" in mount or "#" in mount:
91
+ raise ValueError("mount must be a plain path such as /notes")
92
+ self.mount = mount
93
+ self.allowed_hosts = frozenset(h.strip(".").lower() for h in self.allowed_hosts)
94
+
95
+ @property
96
+ def accepted_hosts(self) -> FrozenSet[str]:
97
+ return frozenset(self.allowed_hosts) | LOOPBACK_NAMES
98
+
99
+
100
+ _log_lock = threading.Lock()
101
+
102
+
103
+ def log_line(app: LoopbackApp, line: str) -> None:
104
+ """Write one line to the app's log. Never pass request bodies, query strings or secrets."""
105
+ if app.log is not None:
106
+ try:
107
+ app.log(line)
108
+ except Exception: # noqa: BLE001 - logging must never break a request
109
+ pass
110
+ if app.log_path is not None:
111
+ stamp = datetime.now().isoformat(timespec="seconds")
112
+ try:
113
+ with _log_lock, open(app.log_path, "a", encoding="utf-8") as fh:
114
+ fh.write(f"{stamp} {line}\n")
115
+ except OSError:
116
+ pass
117
+
118
+
119
+ def _hex(rgb: Tuple[int, int, int]) -> str:
120
+ return "#%02x%02x%02x" % tuple(rgb)
121
+
122
+
123
+ def manifest_of(app: LoopbackApp) -> bytes:
124
+ """The web app manifest: standalone display, the app's colors and its two icons."""
125
+ return json.dumps({
126
+ "name": app.name, "short_name": app.short_name or app.name,
127
+ "start_url": "./", "scope": "./", "display": "standalone",
128
+ "background_color": _hex(app.background), "theme_color": _hex(app.background),
129
+ "icons": [
130
+ {"src": "icon-180.png", "sizes": "180x180", "type": "image/png"},
131
+ {"src": "icon-512.png", "sizes": "512x512", "type": "image/png"},
132
+ ],
133
+ }).encode()
134
+
135
+
136
+ def host_name(header: str) -> str:
137
+ """The host part of a Host header, lower case, without port, brackets or a final dot."""
138
+ value = header.strip().lower()
139
+ if value.startswith("["):
140
+ end = value.find("]")
141
+ return value[1:end] if end > 0 else ""
142
+ if value.count(":") == 1:
143
+ value = value.split(":", 1)[0]
144
+ return value.rstrip(".")
145
+
146
+
147
+ Payload = object
148
+ Route = Callable[["LoopbackHandler", Optional[dict]], Tuple[int, Payload]]
149
+ Routes = Dict[Tuple[str, str], Route]
150
+
151
+
152
+ class LoopbackHandler(BaseHTTPRequestHandler):
153
+ """Request handler for one app. Build it with make_handler(); routes do the app's work."""
154
+
155
+ app: LoopbackApp
156
+ routes: Routes = {}
157
+ index_bytes: bytes = b""
158
+ icons: Dict[str, bytes] = {}
159
+ manifest: bytes = b""
160
+ sys_version = ""
161
+
162
+ # The base class would log raw request lines and parser errors, which can hold secrets.
163
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002 - stdlib signature
164
+ pass
165
+
166
+ def log_request(self, code: object = "-", size: object = "-") -> None:
167
+ command = getattr(self, "command", None)
168
+ method = command if command in METHODS + ("HEAD", "OPTIONS") else "OTHER"
169
+ shown = "<unknown>"
170
+ if hasattr(self, "path"):
171
+ sub = self.sub_path()
172
+ if sub == "redirect":
173
+ shown = self.app.mount
174
+ elif sub in self.known_paths():
175
+ shown = self.app.mount + sub
176
+ log_line(self.app, f"{self.address_string()} {method} {shown} {code}")
177
+
178
+ def known_paths(self) -> set:
179
+ paths = {path for _, path in self.routes}
180
+ return paths | set(STATIC_PATHS) if self.app.web_client else paths
181
+
182
+ def host_ok(self) -> bool:
183
+ hosts = self.headers.get_all("Host", [])
184
+ return len(hosts) == 1 and host_name(hosts[0]) in self.app.accepted_hosts
185
+
186
+ def sub_path(self) -> str:
187
+ """The request path below the mount, or "redirect" for the bare mount."""
188
+ path = self.path.split("?", 1)[0]
189
+ mount = self.app.mount
190
+ if not mount:
191
+ return path
192
+ if path == mount:
193
+ return "redirect"
194
+ return path[len(mount):] if path.startswith(mount + "/") else path
195
+
196
+ def query(self) -> Dict[str, str]:
197
+ """Query parameters, first value of each. Query strings are never logged."""
198
+ raw = self.path.split("?", 1)[1] if "?" in self.path else ""
199
+ return {key: values[0] for key, values in parse_qs(raw, keep_blank_values=True).items()}
200
+
201
+ def accepts_gzip(self) -> bool:
202
+ for part in (self.headers.get("Accept-Encoding") or "").split(","):
203
+ coding, *params = part.split(";")
204
+ if coding.strip().lower() != "gzip":
205
+ continue
206
+ quality = 1.0
207
+ for param in params:
208
+ key, _, value = param.partition("=")
209
+ if key.strip().lower() == "q":
210
+ try:
211
+ quality = float(value)
212
+ except ValueError:
213
+ quality = 0.0
214
+ return quality > 0
215
+ return False
216
+
217
+ def send(self, status: int, body: object, ctype: str = "application/json",
218
+ extra: Optional[Dict[str, str]] = None) -> None:
219
+ """Send a response with no-store caching and the security headers."""
220
+ headers = dict(extra or {})
221
+ if not isinstance(body, (bytes, bytearray)):
222
+ body = json.dumps(body).encode()
223
+ limit = self.app.gzip_min_bytes
224
+ if limit is not None and len(body) >= limit and self.accepts_gzip():
225
+ body = gzip.compress(body, compresslevel=6)
226
+ headers["Content-Encoding"] = "gzip"
227
+ headers["Vary"] = "Accept-Encoding"
228
+ self.send_response(status)
229
+ self.send_header("Content-Type", ctype)
230
+ self.send_header("Content-Length", str(len(body)))
231
+ self.send_header("Cache-Control", "no-store")
232
+ self.send_header("X-Content-Type-Options", "nosniff")
233
+ self.send_header("Referrer-Policy", "no-referrer")
234
+ for key, value in headers.items():
235
+ self.send_header(key, value)
236
+ self.end_headers()
237
+ self.wfile.write(body)
238
+
239
+ def read_json(self) -> dict:
240
+ """One Content-Length, no Transfer-Encoding, a JSON object within app.max_body_bytes."""
241
+ lengths = self.headers.get_all("Content-Length", [])
242
+ if self.headers.get("Transfer-Encoding") is not None or len(lengths) != 1:
243
+ raise ApiError(400, "one Content-Length is required; Transfer-Encoding is unsupported")
244
+ raw = lengths[0].strip()
245
+ if not (raw.isascii() and raw.isdecimal()):
246
+ raise ApiError(400, "bad body size")
247
+ length = int(raw)
248
+ if length > self.app.max_body_bytes:
249
+ raise ApiError(413, "body too large")
250
+ if length <= 0:
251
+ raise ApiError(400, "bad body size")
252
+ payload = self.rfile.read(length)
253
+ if len(payload) != length:
254
+ raise ApiError(400, "body ended early")
255
+ try:
256
+ body = json.loads(payload)
257
+ except (ValueError, RecursionError):
258
+ raise ApiError(400, "body must be JSON") from None
259
+ if not isinstance(body, dict):
260
+ raise ApiError(400, "body must be a JSON object")
261
+ return body
262
+
263
+ def dispatch(self) -> None:
264
+ if not self.host_ok():
265
+ return self.send(403, {"error": "host not allowed"})
266
+ sub = self.sub_path()
267
+ if sub == "redirect":
268
+ return self.send(301, b"", "text/plain", {"Location": self.app.mount + "/"})
269
+ if self.app.web_client and self.command == "GET" and sub in STATIC_PATHS:
270
+ if sub == "/":
271
+ return self.send(200, self.index_bytes, "text/html; charset=utf-8",
272
+ {"Content-Security-Policy": self.app.index_csp})
273
+ if sub == "/manifest.webmanifest":
274
+ return self.send(200, self.manifest, "application/manifest+json")
275
+ return self.send(200, self.icons[sub], "image/png")
276
+ route = self.routes.get((self.command, sub))
277
+ if route is None:
278
+ known = any(path == sub for _, path in self.routes)
279
+ return self.send(405 if known else 404,
280
+ {"error": "method not allowed" if known else "not found"})
281
+ try:
282
+ body = self.read_json() if self.command in ("PUT", "POST") else None
283
+ status, result = route(self, body)
284
+ except ApiError as error:
285
+ return self.send(error.status, error.body)
286
+ except OSError as error:
287
+ log_line(self.app, f"{self.command} {self.app.mount}{sub} failed: {type(error).__name__}")
288
+ return self.send(500, {"error": f"server could not do that: {error.strerror or type(error).__name__}"})
289
+ except Exception as error: # noqa: BLE001 - a bug in a route still gets a JSON answer
290
+ log_line(self.app, f"{self.command} {self.app.mount}{sub} failed: {type(error).__name__}")
291
+ return self.send(500, {"error": "internal error"})
292
+ return self.send(status, result)
293
+
294
+ do_GET = do_PUT = do_POST = do_DELETE = dispatch
295
+
296
+
297
+ def make_handler(app: LoopbackApp, routes: Routes) -> type:
298
+ """Build the handler class for one app. Routes are keyed by (method, path below the mount)."""
299
+ for method, path in routes:
300
+ if method not in METHODS or not path.startswith("/"):
301
+ raise ValueError(f"bad route {(method, path)}: method must be one of {METHODS}, path must start with /")
302
+ index = app.index_html
303
+ if isinstance(index, Path):
304
+ index = index.read_bytes() if index.exists() else None
305
+ if index is None:
306
+ index = f"<!doctype html><title>{app.name}</title><p>{app.name} has no web client yet.</p>".encode()
307
+ mark = app.short_name or app.name
308
+ icons = {f"/icon-{s}.png": pixel_mark_png(mark, s, app.background, app.accent) for s in (180, 512)} \
309
+ if app.web_client else {}
310
+ return type("Handler", (LoopbackHandler,), {
311
+ "app": app, "routes": dict(routes), "index_bytes": bytes(index),
312
+ "icons": icons, "manifest": manifest_of(app) if app.web_client else b"",
313
+ "server_version": app.server_version,
314
+ })
315
+
316
+
317
+ def health_route(check: Optional[Callable[[], dict]] = None, **fields: object) -> Route:
318
+ """GET route answering `{"ok": true, **fields, **check()}`. Clients and installers poll it."""
319
+ def route(_handler: LoopbackHandler, _body: Optional[dict]) -> Tuple[int, dict]:
320
+ return 200, {"ok": True, **fields, **(check() if check else {})}
321
+ return route
322
+
323
+
324
+ def require_bearer(token: str, route: Route) -> Route:
325
+ """Wrap a route so it answers 401 unless `Authorization: Bearer <token>` matches."""
326
+ if not token:
327
+ raise ValueError("token must not be empty")
328
+ expected = token.encode()
329
+
330
+ def guarded(handler: LoopbackHandler, body: Optional[dict]) -> Tuple[int, Payload]:
331
+ supplied = handler.headers.get("Authorization") or ""
332
+ if supplied.startswith("Bearer "):
333
+ supplied = supplied[len("Bearer "):]
334
+ if not hmac.compare_digest(supplied.strip().encode(), expected):
335
+ raise ApiError(401, "unauthorized")
336
+ return route(handler, body)
337
+ return guarded
338
+
339
+
340
+ class LoopbackServer(ThreadingHTTPServer):
341
+ """ThreadingHTTPServer that owns its port alone.
342
+
343
+ The stdlib server sets SO_REUSEADDR, and on Windows that lets a second server bind
344
+ the same port with no error and take some of the first one's requests. On Windows
345
+ this sets SO_EXCLUSIVEADDRUSE instead, so a second bind fails; elsewhere SO_REUSEADDR
346
+ already refuses a second listener.
347
+ """
348
+
349
+ allow_reuse_address = os.name != "nt"
350
+
351
+ def server_bind(self) -> None:
352
+ if os.name == "nt" and hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
353
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
354
+ super().server_bind()
355
+
356
+
357
+ def make_server(app: LoopbackApp, routes: Routes, port: Optional[int] = None) -> LoopbackServer:
358
+ """Bind 127.0.0.1 only (port 0 picks a free one) and return the server, not yet serving."""
359
+ return LoopbackServer((LOOPBACK, app.port if port is None else port), make_handler(app, routes))
360
+
361
+
362
+ def serve(app: LoopbackApp, routes: Routes, port: Optional[int] = None) -> None:
363
+ """Bind 127.0.0.1 only and serve until stopped. A taken port raises OSError."""
364
+ server = make_server(app, routes, port)
365
+ address = f"http://{LOOPBACK}:{server.server_address[1]}{app.mount}/"
366
+ log_line(app, f"listening on {address}")
367
+ if sys.stdout:
368
+ print(f"{app.name} on {address}", flush=True)
369
+ try:
370
+ server.serve_forever()
371
+ finally:
372
+ server.server_close()
@@ -0,0 +1,365 @@
1
+ import gzip
2
+ import http.client
3
+ import json
4
+ import re
5
+ import socket
6
+ import threading
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ import uppercut_loopback_api as api
12
+ from uppercut_loopback_api import ApiError, LoopbackApp
13
+
14
+ TAILNET = "tailnet.example"
15
+ SECRET = "TEST-ONLY-SECRET-9f3a"
16
+
17
+
18
+ class Running:
19
+ def __init__(self, app, routes):
20
+ self.app = app
21
+ self.server = api.make_server(app, routes, port=0)
22
+ self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
23
+ self.thread.start()
24
+
25
+ def close(self):
26
+ self.server.shutdown()
27
+ self.server.server_close()
28
+ self.thread.join(timeout=2)
29
+
30
+ def request(self, method, path, body=None, headers=None, host="127.0.0.1"):
31
+ conn = http.client.HTTPConnection(*self.server.server_address, timeout=3)
32
+ try:
33
+ conn.putrequest(method, path, skip_host=True, skip_accept_encoding=True)
34
+ if host is not None:
35
+ conn.putheader("Host", host)
36
+ headers = headers or {}
37
+ for key, value in headers.items():
38
+ for one in value if isinstance(value, list) else [value]:
39
+ conn.putheader(key, one)
40
+ if body is not None and "Content-Length" not in headers and "Transfer-Encoding" not in headers:
41
+ conn.putheader("Content-Length", str(len(body)))
42
+ conn.endheaders(body)
43
+ response = conn.getresponse()
44
+ return response.status, dict(response.getheaders()), response.read()
45
+ finally:
46
+ conn.close()
47
+
48
+ def json(self, method, path, payload=None, **kw):
49
+ body = json.dumps(payload).encode() if payload is not None else None
50
+ status, headers, raw = self.request(method, path, body, **kw)
51
+ return status, (json.loads(raw) if raw else None)
52
+
53
+
54
+ def echo(_handler, body):
55
+ return 200, {"got": body}
56
+
57
+
58
+ def boom_os(_handler, _body):
59
+ raise PermissionError(13, "Access is denied")
60
+
61
+
62
+ def boom_bug(_handler, _body):
63
+ raise KeyError(SECRET)
64
+
65
+
66
+ def conflict(_handler, _body):
67
+ raise ApiError(409, "changed", revision="abc")
68
+
69
+
70
+ def query_route(handler, _body):
71
+ return 200, handler.query()
72
+
73
+
74
+ @pytest.fixture
75
+ def tmp_log(tmp_path):
76
+ return tmp_path / "requests.log"
77
+
78
+
79
+ @pytest.fixture
80
+ def app(tmp_path, tmp_log):
81
+ index = tmp_path / "index.html"
82
+ index.write_text("<!doctype html><html><title>Notes</title></html>", encoding="utf-8")
83
+ return LoopbackApp(
84
+ name="Notes Remote", short_name="NTS", mount="/notes", port=0,
85
+ allowed_hosts=api.tailnet_hosts(TAILNET, "studio"), index_html=index, log_path=tmp_log,
86
+ max_body_bytes=1024,
87
+ )
88
+
89
+
90
+ @pytest.fixture
91
+ def routes(app):
92
+ return {
93
+ ("GET", "/api/health"): api.health_route(lambda: {"exists": True}, app="notes"),
94
+ ("PUT", "/api/echo"): echo,
95
+ ("POST", "/api/echo"): echo,
96
+ ("GET", "/api/os"): boom_os,
97
+ ("GET", "/api/bug"): boom_bug,
98
+ ("GET", "/api/conflict"): conflict,
99
+ ("GET", "/api/query"): query_route,
100
+ ("GET", "/api/secret"): api.require_bearer(SECRET, api.health_route()),
101
+ ("GET", "/api/big"): lambda h, b: (200, {"items": ["x" * 50] * 100}),
102
+ }
103
+
104
+
105
+ @pytest.fixture
106
+ def run(app, routes):
107
+ running = Running(app, routes)
108
+ yield running
109
+ running.close()
110
+
111
+
112
+ # ---------------------------------------------------------------- Host check
113
+
114
+
115
+ def test_unknown_host_is_refused(run):
116
+ assert run.json("GET", "/notes/api/health", host="evil.example") == (403, {"error": "host not allowed"})
117
+
118
+
119
+ @pytest.mark.parametrize("host", [
120
+ "studio", "studio.tailnet.example", "STUDIO.tailnet.example:443", "studio.tailnet.example.",
121
+ "127.0.0.1", "127.0.0.1:8890", "localhost", "localhost:8890",
122
+ ])
123
+ def test_tailnet_and_loopback_hosts_pass(run, host):
124
+ assert run.json("GET", "/notes/api/health", host=host)[0] == 200
125
+
126
+
127
+ def test_missing_or_repeated_host_is_refused(run):
128
+ assert run.json("GET", "/notes/api/health", host=None)[0] == 403
129
+ status, _ = run.json("GET", "/notes/api/health", host="127.0.0.1", headers={"Host": "evil.example"})
130
+ assert status == 403
131
+
132
+
133
+ def test_host_name_parsing():
134
+ assert api.host_name("[::1]:8080") == "::1"
135
+ assert api.host_name("[::1]") == "::1"
136
+ assert api.host_name("Studio.Tailnet.example.:443") == "studio.tailnet.example"
137
+ assert api.host_name("::1") == "::1"
138
+
139
+
140
+ def test_only_loopback_names_without_configuration():
141
+ assert LoopbackApp(name="X", port=1).accepted_hosts == {"127.0.0.1", "localhost"}
142
+
143
+
144
+ def test_tailnet_hosts_builds_short_and_full_names():
145
+ assert api.tailnet_hosts("Tailnet.Example.", "studio", "notes") == {
146
+ "studio", "studio.tailnet.example", "notes", "notes.tailnet.example"}
147
+
148
+
149
+ def test_package_names_no_tailnet():
150
+ source = Path(api.__file__).parent
151
+ for path in source.glob("*.py"):
152
+ text = path.read_text(encoding="utf-8")
153
+ assert not re.search(r"\.ts\.net", text, re.IGNORECASE), path.name
154
+ assert "0.0.0.0" not in text, path.name
155
+
156
+
157
+ # ---------------------------------------------------------------- binding
158
+
159
+
160
+ def test_binds_loopback_only(run):
161
+ assert run.server.server_address[0] == "127.0.0.1"
162
+
163
+
164
+ def test_a_second_server_cannot_share_the_port(run, app, routes):
165
+ with pytest.raises(OSError):
166
+ second = api.make_server(app, routes, port=run.server.server_address[1])
167
+ second.server_close()
168
+
169
+
170
+ def test_bad_routes_are_refused(app):
171
+ with pytest.raises(ValueError):
172
+ api.make_handler(app, {("PATCH", "/x"): echo})
173
+ with pytest.raises(ValueError):
174
+ api.make_handler(app, {("GET", "x"): echo})
175
+
176
+
177
+ # ---------------------------------------------------------------- mount and static client
178
+
179
+
180
+ def test_mount_redirects_and_routes_work_with_or_without_it(run):
181
+ status, headers, _ = run.request("GET", "/notes")
182
+ assert (status, headers["Location"]) == (301, "/notes/")
183
+ assert run.json("GET", "/notes/api/health") == (200, {"ok": True, "app": "notes", "exists": True})
184
+ assert run.json("GET", "/api/health")[0] == 200
185
+
186
+
187
+ @pytest.mark.parametrize("given, expected", [("", ""), ("/", ""), ("notes", "/notes"), ("/notes/", "/notes")])
188
+ def test_mount_is_normalized(given, expected):
189
+ assert LoopbackApp(name="X", port=1, mount=given).mount == expected
190
+
191
+
192
+ def test_root_mount_serves_routes_at_the_root(tmp_log):
193
+ app = LoopbackApp(name="Feed", port=0, web_client=False, log_path=tmp_log)
194
+ running = Running(app, {("GET", "/v1/health"): api.health_route(version="1.0.0")})
195
+ try:
196
+ assert running.json("GET", "/v1/health") == (200, {"ok": True, "version": "1.0.0"})
197
+ assert running.json("GET", "/")[0] == 404
198
+ assert running.json("GET", "/manifest.webmanifest")[0] == 404
199
+ finally:
200
+ running.close()
201
+ assert "GET /v1/health 200" in tmp_log.read_text(encoding="utf-8")
202
+
203
+
204
+ def test_index_has_csp_and_no_store(run):
205
+ status, headers, body = run.request("GET", "/notes/")
206
+ assert status == 200
207
+ assert "frame-ancestors 'none'" in headers["Content-Security-Policy"]
208
+ assert headers["Cache-Control"] == "no-store"
209
+ assert headers["X-Content-Type-Options"] == "nosniff"
210
+ assert headers["Referrer-Policy"] == "no-referrer"
211
+ assert b"<html" in body
212
+
213
+
214
+ def test_missing_index_gets_a_placeholder(tmp_path):
215
+ app = LoopbackApp(name="Notes Remote", port=0, index_html=tmp_path / "absent.html")
216
+ running = Running(app, {})
217
+ try:
218
+ status, _, body = running.request("GET", "/")
219
+ assert status == 200 and b"no web client yet" in body
220
+ finally:
221
+ running.close()
222
+
223
+
224
+ def test_manifest_and_icons(run):
225
+ status, _, raw = run.request("GET", "/notes/manifest.webmanifest")
226
+ manifest = json.loads(raw)
227
+ assert (status, manifest["name"], manifest["short_name"], manifest["display"]) == (
228
+ 200, "Notes Remote", "NTS", "standalone")
229
+ for size in (180, 512):
230
+ status, headers, raw = run.request("GET", f"/notes/icon-{size}.png")
231
+ assert (status, headers["Content-Type"], raw[:8]) == (200, "image/png", b"\x89PNG\r\n\x1a\n")
232
+ assert int.from_bytes(raw[16:20], "big") == size
233
+
234
+
235
+ def test_unknown_path_and_wrong_method(run):
236
+ assert run.json("GET", "/notes/api/nope") == (404, {"error": "not found"})
237
+ assert run.json("DELETE", "/notes/api/echo") == (405, {"error": "method not allowed"})
238
+
239
+
240
+ # ---------------------------------------------------------------- bodies
241
+
242
+
243
+ def test_json_object_body_reaches_the_route(run):
244
+ assert run.json("PUT", "/notes/api/echo", {"a": 1}) == (200, {"got": {"a": 1}})
245
+
246
+
247
+ @pytest.mark.parametrize("headers, body, expected", [
248
+ ({"Content-Length": "abc"}, b"{}", 400),
249
+ ({"Content-Length": "-1"}, b"{}", 400),
250
+ ({"Content-Length": "0"}, b"", 400),
251
+ ({"Content-Length": "+2"}, b"{}", 400),
252
+ ({"Content-Length": ["2", "2"]}, b"{}", 400),
253
+ ({"Transfer-Encoding": "chunked"}, b"2\r\n{}\r\n0\r\n\r\n", 400),
254
+ ({"Content-Length": "1025"}, b"", 413),
255
+ ])
256
+ def test_body_framing_is_strict(run, headers, body, expected):
257
+ assert run.request("PUT", "/notes/api/echo", body, headers)[0] == expected
258
+
259
+
260
+ @pytest.mark.parametrize("body", [b"[1]", b"{not json", b'"text"', b"[" * 1000], ids=["list", "bad", "string", "deep"])
261
+ def test_body_must_be_a_json_object(run, body):
262
+ assert run.request("POST", "/notes/api/echo", body)[0] == 400
263
+
264
+
265
+ def test_short_body_is_refused(run):
266
+ with socket.create_connection(run.server.server_address, timeout=3) as sock:
267
+ sock.sendall(b"PUT /notes/api/echo HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 10\r\n\r\n{}")
268
+ sock.shutdown(socket.SHUT_WR)
269
+ reply = sock.recv(4096)
270
+ assert reply.startswith(b"HTTP/1.0 400")
271
+
272
+
273
+ # ---------------------------------------------------------------- errors
274
+
275
+
276
+ def test_api_error_carries_extra_fields(run):
277
+ assert run.json("GET", "/notes/api/conflict") == (409, {"error": "changed", "revision": "abc"})
278
+
279
+
280
+ def test_os_error_is_a_500_with_the_reason(run):
281
+ assert run.json("GET", "/notes/api/os") == (500, {"error": "server could not do that: Access is denied"})
282
+
283
+
284
+ def test_a_bug_in_a_route_is_a_plain_500_and_its_message_is_not_logged(run, tmp_log):
285
+ assert run.json("GET", "/notes/api/bug") == (500, {"error": "internal error"})
286
+ text = tmp_log.read_text(encoding="utf-8")
287
+ assert "failed: KeyError" in text and SECRET not in text
288
+
289
+
290
+ # ---------------------------------------------------------------- logging
291
+
292
+
293
+ def test_log_never_holds_bodies_queries_headers_or_unknown_paths(run, tmp_log):
294
+ run.json("PUT", "/notes/api/echo", {"content": SECRET})
295
+ run.request("GET", f"/notes/api/query?token={SECRET}")
296
+ run.request("GET", f"/notes/{SECRET}")
297
+ run.request("GET", "/notes/api/secret", headers={"Authorization": f"Bearer {SECRET}"})
298
+ run.request("BREW", f"/notes/{SECRET}")
299
+ text = tmp_log.read_text(encoding="utf-8")
300
+ assert SECRET not in text
301
+ assert "PUT /notes/api/echo 200" in text
302
+ assert "GET /notes/api/query 200" in text
303
+ assert "<unknown>" in text
304
+ assert "OTHER" in text
305
+
306
+
307
+ def test_log_callable_gets_the_same_lines(tmp_path):
308
+ lines = []
309
+ app = LoopbackApp(name="X", port=0, web_client=False, log=lines.append)
310
+ running = Running(app, {("GET", "/ping"): api.health_route()})
311
+ try:
312
+ running.request("GET", "/ping?x=1")
313
+ finally:
314
+ running.close()
315
+ assert any(line.endswith("GET /ping 200") for line in lines)
316
+
317
+
318
+ def test_query_parameters(run):
319
+ assert run.json("GET", "/notes/api/query?id=a&id=b&empty=") == (200, {"id": "a", "empty": ""})
320
+
321
+
322
+ # ---------------------------------------------------------------- bearer token and gzip
323
+
324
+
325
+ def test_bearer_token(run):
326
+ assert run.json("GET", "/notes/api/secret") == (401, {"error": "unauthorized"})
327
+ assert run.json("GET", "/notes/api/secret", headers={"Authorization": "Bearer wrong"})[0] == 401
328
+ assert run.json("GET", "/notes/api/secret", headers={"Authorization": f"Bearer {SECRET}"}) == (200, {"ok": True})
329
+ with pytest.raises(ValueError):
330
+ api.require_bearer("", echo)
331
+
332
+
333
+ def test_gzip_only_when_enabled_accepted_and_large_enough(app, routes):
334
+ app.gzip_min_bytes = 1000
335
+ running = Running(app, routes)
336
+ try:
337
+ status, headers, raw = running.request("GET", "/notes/api/big", headers={"Accept-Encoding": "br, gzip"})
338
+ assert (status, headers["Content-Encoding"], headers["Vary"]) == (200, "gzip", "Accept-Encoding")
339
+ assert len(json.loads(gzip.decompress(raw))["items"]) == 100
340
+ assert "Content-Encoding" not in running.request(
341
+ "GET", "/notes/api/big", headers={"Accept-Encoding": "gzip;q=0"})[1]
342
+ assert "Content-Encoding" not in running.request(
343
+ "GET", "/notes/api/health", headers={"Accept-Encoding": "gzip"})[1]
344
+ finally:
345
+ running.close()
346
+
347
+
348
+ def test_gzip_off_by_default(run):
349
+ assert "Content-Encoding" not in run.request("GET", "/notes/api/big", headers={"Accept-Encoding": "gzip"})[1]
350
+
351
+
352
+ # ---------------------------------------------------------------- pixel mark
353
+
354
+
355
+ def test_every_glyph_is_five_by_seven():
356
+ for ch, rows in api.GLYPHS.items():
357
+ parts = rows.split()
358
+ assert len(parts) == 7, ch
359
+ assert all(len(r) == 5 and set(r) <= {"0", "1"} for r in parts), ch
360
+
361
+
362
+ def test_pixel_mark_png_size_and_plain_tile():
363
+ png = api.pixel_mark_png("ram", 64, (0, 0, 0), (255, 255, 255))
364
+ assert png[:8] == b"\x89PNG\r\n\x1a\n" and int.from_bytes(png[16:20], "big") == 64
365
+ assert api.pixel_mark_png("???", 32, (0, 0, 0), (9, 9, 9)) == api.pixel_mark_png("", 32, (0, 0, 0), (1, 1, 1))