Report relay: files the app's bug reports as Gitea issues
tools/report-relay is a dependency-free Python service. It takes the JSON the app's Bug report button sends, validates it (type, text, context and log sizes), scrubs the log a second time, rate-limits (5 per client IP and 60 in all per hour, 4 in flight), neutralises @mentions, and files one issue in blueflare/alkane-toolkit with the labels bug/ui/feature and from-app. It stores nothing and logs one line per report without its text. It runs on the Gitea host behind the shared nginx at https://gitea.bluefla.re/alkane-report/ as the scoped alkane-reporter bot (team alkane-reporters: issues write, code read, alkane-toolkit only). See tools/report-relay/README.md. Its tests run in verify's unit-test step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdKQBRg6YCM1XXQCTnD5GF
This commit is contained in:
@@ -159,6 +159,7 @@ jobs:
|
||||
run: |
|
||||
cargo test -p alkane-gui --offline
|
||||
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
|
||||
python3 tools/report-relay/test_relay.py
|
||||
|
||||
- name: Microbenchmarks
|
||||
if: steps.surface.outputs.surface == 'full'
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Report relay for the Alkane Toolkit's Bug report button (see README.md).
|
||||
FROM python:3.13-alpine
|
||||
RUN adduser -D -H -u 10001 relay
|
||||
COPY relay.py /app/relay.py
|
||||
USER relay
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["python3", "-u", "/app/relay.py"]
|
||||
@@ -0,0 +1,65 @@
|
||||
# Report relay
|
||||
|
||||
Files the app's bug reports and feature requests as issues in
|
||||
`blueflare/alkane-toolkit`. The app's **Bug report** button posts the report
|
||||
here; the relay holds the only token, so the public app download carries no
|
||||
secret.
|
||||
|
||||
```
|
||||
app --HTTPS--> gitea.bluefla.re/alkane-report/ (nginx) --> relay --> Gitea API
|
||||
```
|
||||
|
||||
## What it does
|
||||
|
||||
- `POST /v1/report` takes the JSON the app sends (`kind`, `text`, version and
|
||||
OS context, optional `log`) and answers `201 {"number", "url"}` or an error
|
||||
`{"error": "..."}` the app shows as is. `GET /healthz` answers `200`.
|
||||
- Checks: type is `bug`, `ui` or `feature`; text 1 to 8,000 characters;
|
||||
each context value at most 120 printable characters; log at most 16 KiB;
|
||||
body at most 64 KiB (nginx enforces the same).
|
||||
- Rate limits, in memory: 5 reports per client IP per hour and 60 in all.
|
||||
Over the limit: `429` with `Retry-After`. At most 4 reports in flight.
|
||||
The client IP is `X-Real-IP` from nginx. Office LAN clients reach nginx
|
||||
through the router's hairpin NAT, so they share one IP and one limit.
|
||||
- Scrubs the log a second time (the app scrubs first): password, token,
|
||||
secret and similar values, `Authorization`/`Cookie` values, URL passwords
|
||||
and PEM private keys become `[redacted]`.
|
||||
- `@name` in a report cannot notify anyone (a zero-width space follows `@`).
|
||||
- The issue title is the text's first line (up to 100 characters). The body
|
||||
has the type, a context table, the text, and the log in a collapsed block.
|
||||
Labels: the type (`bug`, `ui`, `feature`) and `from-app`.
|
||||
- Nothing is stored. Each report leaves one log line: the client IP and the
|
||||
outcome (`filed #N`, `refused <status>`, `rate limited`, `tracker error`),
|
||||
never the report's text.
|
||||
|
||||
## Gitea account
|
||||
|
||||
Issues are filed as `alkane-reporter`, a local non-admin user with a random
|
||||
password that is never used. Its only access is the org team
|
||||
`alkane-reporters` (units `repo.code: read`, `repo.issues: write`) on
|
||||
`alkane-toolkit`. Its token `alkane-toolkit-bug-reports` has the scopes
|
||||
`write:issue` and `read:repository`. This mirrors FLARE's `flare-reporter`.
|
||||
|
||||
## Deployment
|
||||
|
||||
On the Gitea host, recorded in the `flare-deployment` repository
|
||||
(`runbooks/alkane-report-relay.md`):
|
||||
|
||||
```sh
|
||||
# in /opt/flare/deploy/alkane-report-relay, holding relay.py, Dockerfile, compose.yml
|
||||
PROXY_NETWORK=flare_default docker compose -p alkane-report-relay up -d --build
|
||||
```
|
||||
|
||||
The token file is `secrets/gitea_token` next to the compose file (directory
|
||||
`0700`, never committed). nginx routes `location /alkane-report/` in the
|
||||
`gitea.bluefla.re` server block to `alkane-report-relay:8080`.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
python3 tools/report-relay/test_relay.py
|
||||
```
|
||||
|
||||
They run the real HTTP handler against a fake Gitea: filing, scrubbing,
|
||||
mention handling, validation, size and rate limits, and tracker errors. CI
|
||||
runs them in the `verify` workflow's unit tests.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Deployed on the Gitea host next to the shared nginx (see README.md).
|
||||
# The token file is created on the host and never committed.
|
||||
services:
|
||||
report-relay:
|
||||
build: .
|
||||
image: alkane-report-relay:local
|
||||
container_name: alkane-report-relay
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
environment:
|
||||
GITEA_URL: http://gitea:3000
|
||||
GITEA_REPO: blueflare/alkane-toolkit
|
||||
GITEA_TOKEN_FILE: /run/secrets/gitea_token
|
||||
RATE_PER_IP: "5"
|
||||
RATE_GLOBAL: "60"
|
||||
volumes:
|
||||
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
|
||||
networks: [proxy]
|
||||
networks:
|
||||
proxy:
|
||||
external: true
|
||||
name: ${PROXY_NETWORK:?set PROXY_NETWORK to the shared nginx network}
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Report relay: files Alkane Toolkit bug reports as Gitea issues.
|
||||
|
||||
The app's Bug report button posts JSON here; the relay checks it, scrubs the
|
||||
log again, rate-limits, and files one issue in one repository with its own
|
||||
token. The app holds no secret. Nothing about a report is stored.
|
||||
|
||||
POST /v1/report {"kind": "bug"|"ui"|"feature", "text": "...",
|
||||
"app_version", "platform", "os", "appearance",
|
||||
"language", "window": "...", "log": "..."}
|
||||
-> 201 {"number": N, "url": "..."}
|
||||
-> 4xx/5xx {"error": "reason the app shows"}
|
||||
GET /healthz -> 200 ok
|
||||
|
||||
Configuration (environment):
|
||||
GITEA_URL API base, e.g. http://gitea:3000 (default https://gitea.bluefla.re)
|
||||
GITEA_REPO owner/name the issues go to (default blueflare/alkane-toolkit)
|
||||
GITEA_TOKEN_FILE file holding the token (scopes write:issue, read:repository)
|
||||
LISTEN host:port (default 0.0.0.0:8080)
|
||||
RATE_PER_IP reports per client IP per hour (default 5)
|
||||
RATE_GLOBAL reports per hour in all (default 60)
|
||||
|
||||
The client IP is the X-Real-IP header the reverse proxy sets; the relay must
|
||||
only be reachable through that proxy.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KINDS = {"bug": "Bug", "ui": "UI change", "feature": "Feature request"}
|
||||
CONTEXT_FIELDS = (
|
||||
("app_version", "App version"),
|
||||
("platform", "Platform"),
|
||||
("os", "OS"),
|
||||
("appearance", "Appearance"),
|
||||
("language", "Language"),
|
||||
("window", "Window"),
|
||||
)
|
||||
FROM_APP_LABEL = "from-app"
|
||||
MAX_BODY = 64 * 1024
|
||||
MAX_TEXT_CHARS = 8000
|
||||
MAX_CONTEXT_CHARS = 120
|
||||
MAX_LOG_BYTES = 16 * 1024
|
||||
MAX_TITLE_CHARS = 100
|
||||
MAX_IN_FLIGHT = 4
|
||||
HOUR = 3600.0
|
||||
|
||||
SECRET_NAME = re.compile(
|
||||
r"(password|passwd|pass|pwd|secret|token|apikey|api_key|psk|credential)"
|
||||
r"(['\"]?\s*[:=]\s*['\"]?)([^\s'\",&;]+)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
HEADER_SECRET = re.compile(r"((?:authorization|cookie)\s*:\s*).+", re.IGNORECASE)
|
||||
URL_USERINFO = re.compile(r"(://[^/\s:@]+:)[^/\s@]+(@)")
|
||||
PEM_BLOCK = re.compile(
|
||||
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(-----END [A-Z ]*PRIVATE KEY-----|\Z)",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def scrub(text: str) -> str:
|
||||
"""Remove credentials (the app scrubs too; this is the second pass)."""
|
||||
text = PEM_BLOCK.sub("[redacted]", text)
|
||||
text = HEADER_SECRET.sub(r"\1[redacted]", text)
|
||||
text = URL_USERINFO.sub(r"\1[redacted]\2", text)
|
||||
return SECRET_NAME.sub(r"\1\2[redacted]", text)
|
||||
|
||||
|
||||
def no_mentions(text: str) -> str:
|
||||
"""Stop @name in a report from notifying Gitea users."""
|
||||
return re.sub(r"@(?=[A-Za-z0-9_])", "@\u200b", text)
|
||||
|
||||
|
||||
def fence_for(text: str) -> str:
|
||||
"""A backtick fence longer than any backtick run in `text`."""
|
||||
longest = max((len(m) for m in re.findall(r"`+", text)), default=0)
|
||||
return "`" * max(3, longest + 1)
|
||||
|
||||
|
||||
def cell(value: str) -> str:
|
||||
return value.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
class BadReport(Exception):
|
||||
def __init__(self, status: int, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
def validate(raw: bytes) -> dict:
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise BadReport(400, "The report was not valid JSON")
|
||||
if not isinstance(data, dict):
|
||||
raise BadReport(400, "The report was not a JSON object")
|
||||
kind = data.get("kind", "bug")
|
||||
if kind not in KINDS:
|
||||
raise BadReport(422, "Unknown report type")
|
||||
text = data.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise BadReport(422, "The report is empty")
|
||||
text = text.strip()
|
||||
if len(text) > MAX_TEXT_CHARS:
|
||||
raise BadReport(413, f"The text is longer than {MAX_TEXT_CHARS} characters")
|
||||
context = {}
|
||||
for key, _ in CONTEXT_FIELDS:
|
||||
value = data.get(key, "")
|
||||
if not isinstance(value, str) or len(value) > MAX_CONTEXT_CHARS:
|
||||
raise BadReport(422, f"Bad value for {key}")
|
||||
context[key] = "".join(c for c in value if c.isprintable())
|
||||
log = data.get("log", "")
|
||||
if not isinstance(log, str) or len(log.encode()) > MAX_LOG_BYTES:
|
||||
raise BadReport(413, "The log is too large")
|
||||
return {"kind": kind, "text": text, "context": context, "log": log}
|
||||
|
||||
|
||||
def issue_title(report: dict) -> str:
|
||||
first = next(line.strip() for line in report["text"].splitlines() if line.strip())
|
||||
if len(first) > MAX_TITLE_CHARS:
|
||||
first = first[: MAX_TITLE_CHARS - 3].rstrip() + "..."
|
||||
return no_mentions(first)
|
||||
|
||||
|
||||
def issue_body(report: dict) -> str:
|
||||
ctx = report["context"]
|
||||
lines = [
|
||||
f"**Type:** {KINDS[report['kind']]}",
|
||||
"",
|
||||
"Sent from the Alkane Toolkit app's Bug report button.",
|
||||
"",
|
||||
"| | |",
|
||||
"|---|---|",
|
||||
]
|
||||
for key, label in CONTEXT_FIELDS:
|
||||
if ctx.get(key):
|
||||
lines.append(f"| {label} | {cell(ctx[key])} |")
|
||||
lines += ["", "---", "", no_mentions(report["text"])]
|
||||
log = scrub(report["log"]).strip()
|
||||
if log:
|
||||
fence = fence_for(log)
|
||||
lines += [
|
||||
"",
|
||||
"<details><summary>Recent activity log</summary>",
|
||||
"",
|
||||
fence,
|
||||
no_mentions(log),
|
||||
fence,
|
||||
"",
|
||||
"</details>",
|
||||
]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""Sliding one-hour windows, per client IP and in all."""
|
||||
|
||||
def __init__(self, per_ip: int, total: int, clock=time.monotonic):
|
||||
self.per_ip, self.total, self.clock = per_ip, total, clock
|
||||
self.by_ip: dict[str, deque] = {}
|
||||
self.all: deque = deque()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def take(self, ip: str) -> float:
|
||||
"""0 if the report may go now, else seconds until it may."""
|
||||
now = self.clock()
|
||||
with self.lock:
|
||||
for q in [self.all, *self.by_ip.values()]:
|
||||
while q and now - q[0] >= HOUR:
|
||||
q.popleft()
|
||||
self.by_ip = {k: q for k, q in self.by_ip.items() if q}
|
||||
mine = self.by_ip.setdefault(ip, deque())
|
||||
if len(mine) >= self.per_ip:
|
||||
return HOUR - (now - mine[0])
|
||||
if len(self.all) >= self.total:
|
||||
return HOUR - (now - self.all[0])
|
||||
mine.append(now)
|
||||
self.all.append(now)
|
||||
return 0.0
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, url: str, repo: str, token: str, timeout: float = 20):
|
||||
self.api = url.rstrip("/") + "/api/v1/repos/" + repo
|
||||
self.token, self.timeout = token, timeout
|
||||
self.labels: dict[str, int] = {}
|
||||
self.labels_at = 0.0
|
||||
|
||||
def _call(self, method: str, path: str, body: dict | None = None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(self.api + path, data=data, method=method)
|
||||
req.add_header("Authorization", f"token {self.token}")
|
||||
req.add_header("Accept", "application/json")
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
return json.load(resp)
|
||||
|
||||
def label_ids(self, names: list[str]) -> list[int]:
|
||||
"""IDs of the repository's labels by name (cached 10 minutes);
|
||||
unknown names are skipped."""
|
||||
if time.monotonic() - self.labels_at > 600:
|
||||
try:
|
||||
found = self._call("GET", "/labels?limit=50")
|
||||
self.labels = {l["name"]: l["id"] for l in found}
|
||||
self.labels_at = time.monotonic()
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError):
|
||||
pass
|
||||
return [self.labels[n] for n in names if n in self.labels]
|
||||
|
||||
def file(self, title: str, body: str, labels: list[str]) -> tuple[int, str]:
|
||||
issue = self._call("POST", "/issues", {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"labels": self.label_ids(labels),
|
||||
})
|
||||
return int(issue["number"]), str(issue["html_url"])
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, gitea: Gitea, limiter: RateLimiter, log=print):
|
||||
self.gitea, self.limiter, self.log = gitea, limiter, log
|
||||
self.slots = threading.BoundedSemaphore(MAX_IN_FLIGHT)
|
||||
|
||||
def handle(self, ip: str, raw: bytes) -> tuple[int, dict, dict]:
|
||||
"""Return (status, json body, extra headers)."""
|
||||
try:
|
||||
report = validate(raw)
|
||||
except BadReport as bad:
|
||||
self.log(f"report from {ip}: refused {bad.status} ({bad.message})")
|
||||
return bad.status, {"error": bad.message}, {}
|
||||
wait = self.limiter.take(ip)
|
||||
if wait > 0:
|
||||
self.log(f"report from {ip}: rate limited")
|
||||
return 429, {"error": "Too many reports; try again later"}, {
|
||||
"Retry-After": str(int(wait) + 1)}
|
||||
if not self.slots.acquire(blocking=False):
|
||||
return 503, {"error": "The report service is busy; try again shortly"}, {}
|
||||
try:
|
||||
number, url = self.gitea.file(
|
||||
issue_title(report), issue_body(report), [report["kind"], FROM_APP_LABEL])
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
|
||||
self.log(f"report from {ip}: tracker error ({type(e).__name__})")
|
||||
return 502, {"error": "The issue tracker did not answer; check the issue "
|
||||
"list before sending again"}, {}
|
||||
finally:
|
||||
self.slots.release()
|
||||
self.log(f"report from {ip}: filed #{number}")
|
||||
return 201, {"number": number, "url": url}, {}
|
||||
|
||||
|
||||
def make_handler(relay: Relay):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "alkane-report-relay"
|
||||
sys_version = ""
|
||||
|
||||
def _send(self, status: int, body: dict, headers: dict | None = None):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/healthz":
|
||||
self._send(200, {"status": "ok"})
|
||||
else:
|
||||
self._send(404, {"error": "Not found"})
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/v1/report":
|
||||
return self._send(404, {"error": "Not found"})
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", ""))
|
||||
except ValueError:
|
||||
return self._send(411, {"error": "Length required"})
|
||||
if length < 0 or length > MAX_BODY:
|
||||
return self._send(413, {"error": "The report is too large"})
|
||||
raw = self.rfile.read(length)
|
||||
ip = self.headers.get("X-Real-IP") or self.client_address[0]
|
||||
status, body, headers = relay.handle(ip, raw)
|
||||
self._send(status, body, headers)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass # one line per report comes from Relay.handle instead
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main() -> None:
|
||||
token_file = os.environ.get("GITEA_TOKEN_FILE", "/run/secrets/gitea_token")
|
||||
with open(token_file) as fh:
|
||||
token = fh.read().strip()
|
||||
if not token:
|
||||
sys.exit(f"empty token in {token_file}")
|
||||
gitea = Gitea(os.environ.get("GITEA_URL", "https://gitea.bluefla.re"),
|
||||
os.environ.get("GITEA_REPO", "blueflare/alkane-toolkit"), token)
|
||||
limiter = RateLimiter(int(os.environ.get("RATE_PER_IP", "5")),
|
||||
int(os.environ.get("RATE_GLOBAL", "60")))
|
||||
relay = Relay(gitea, limiter, log=lambda m: print(m, flush=True))
|
||||
host, _, port = os.environ.get("LISTEN", "0.0.0.0:8080").rpartition(":")
|
||||
server = ThreadingHTTPServer((host or "0.0.0.0", int(port)), make_handler(relay))
|
||||
print(f"report relay on {host}:{port} -> {gitea.api}", flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Tests for the report relay: python3 tools/report-relay/test_relay.py"""
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
import relay # noqa: E402
|
||||
|
||||
TOKEN = "test-token-123"
|
||||
|
||||
|
||||
class FakeGitea:
|
||||
"""Records issue creations; serves the repository's labels."""
|
||||
|
||||
def __init__(self, fail=False):
|
||||
self.created = []
|
||||
self.fail = fail
|
||||
outer = self
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _json(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
||||
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||
{"name": "feature", "id": 3},
|
||||
{"name": "from-app", "id": 9}])
|
||||
self._json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if outer.fail:
|
||||
return self._json(500, {"message": "boom"})
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
outer.created.append((self.path, body))
|
||||
n = len(outer.created)
|
||||
self._json(201, {"number": n,
|
||||
"html_url": f"https://gitea.example/blueflare/alkane-toolkit/issues/{n}"})
|
||||
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
class RelayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.gitea = FakeGitea()
|
||||
self.now = [1000.0]
|
||||
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
||||
self.logs = []
|
||||
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
|
||||
self.limiter, log=self.logs.append)
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.gitea.close()
|
||||
|
||||
def post(self, body, ip="198.51.100.7", path="/v1/report", raw=None):
|
||||
data = raw if raw is not None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(self.url + path, data=data, method="POST",
|
||||
headers={"Content-Type": "application/json",
|
||||
"X-Real-IP": ip})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, json.load(resp), resp.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.load(e), e.headers
|
||||
|
||||
def report(self, **over):
|
||||
body = {"kind": "bug", "text": "Table is blank on macOS\nSteps: open the app.",
|
||||
"app_version": "0.110.0", "platform": "macos-aarch64", "os": "macOS 15.1",
|
||||
"appearance": "dark", "language": "en", "window": "1280x800", "log": ""}
|
||||
body.update(over)
|
||||
return body
|
||||
|
||||
def test_files_an_issue_with_title_body_and_labels(self):
|
||||
status, body, _ = self.post(self.report(kind="feature", log="12:00 scan done"))
|
||||
self.assertEqual(status, 201)
|
||||
self.assertEqual(body["number"], 1)
|
||||
self.assertTrue(body["url"].endswith("/issues/1"))
|
||||
path, issue = self.gitea.created[0]
|
||||
self.assertEqual(path, "/api/v1/repos/blueflare/alkane-toolkit/issues")
|
||||
self.assertEqual(issue["title"], "Table is blank on macOS")
|
||||
self.assertEqual(issue["labels"], [3, 9])
|
||||
self.assertIn("**Type:** Feature request", issue["body"])
|
||||
self.assertIn("| OS | macOS 15.1 |", issue["body"])
|
||||
self.assertIn("Steps: open the app.", issue["body"])
|
||||
self.assertIn("<details><summary>Recent activity log</summary>", issue["body"])
|
||||
self.assertIn("filed #1", self.logs[-1])
|
||||
self.assertNotIn("blank", " ".join(self.logs), "report text is never logged")
|
||||
|
||||
def test_scrubs_the_log_and_neutralises_mentions(self):
|
||||
log = ("set pool url=stratum+tcp://w:hunter2@pool:3333 password=hunter2\n"
|
||||
"Authorization: Bearer abc.def\n``` fence ```")
|
||||
status, _, _ = self.post(self.report(text="@admin please look", log=log))
|
||||
self.assertEqual(status, 201)
|
||||
_, issue = self.gitea.created[0]
|
||||
self.assertNotIn("hunter2", issue["body"])
|
||||
self.assertNotIn("abc.def", issue["body"])
|
||||
self.assertNotIn("@admin", issue["body"])
|
||||
self.assertNotIn("@admin", issue["title"])
|
||||
self.assertIn("````\n", issue["body"], "fence longer than the log's own")
|
||||
|
||||
def test_rejects_bad_reports(self):
|
||||
cases = [
|
||||
(self.report(text=" "), 422),
|
||||
(self.report(kind="hack"), 422),
|
||||
(self.report(text="x" * 8001), 413),
|
||||
(self.report(log="y" * (16 * 1024 + 1)), 413),
|
||||
(self.report(os="z" * 121), 422),
|
||||
(self.report(os=5), 422),
|
||||
([1, 2], 400),
|
||||
]
|
||||
for body, want in cases:
|
||||
status, answer, _ = self.post(body)
|
||||
self.assertEqual(status, want, body if not isinstance(body, dict) else answer)
|
||||
self.assertIn("error", answer)
|
||||
status, _, _ = self.post(None, raw=b"{not json")
|
||||
self.assertEqual(status, 400)
|
||||
status, _, _ = self.post(None, raw=b"x" * (relay.MAX_BODY + 1))
|
||||
self.assertEqual(status, 413)
|
||||
status, _, _ = self.post(self.report(), path="/v1/other")
|
||||
self.assertEqual(status, 404)
|
||||
self.assertEqual(self.gitea.created, [])
|
||||
|
||||
def test_rate_limits_per_ip_and_in_all(self):
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.post(self.report())[0], 201)
|
||||
status, body, headers = self.post(self.report())
|
||||
self.assertEqual(status, 429)
|
||||
self.assertGreater(int(headers["Retry-After"]), 0)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.9")[0], 201)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.10")[0], 429, "global cap of 3")
|
||||
self.now[0] += relay.HOUR
|
||||
self.assertEqual(self.post(self.report())[0], 201, "window slides")
|
||||
|
||||
def test_tracker_failure_is_reported(self):
|
||||
self.gitea.fail = True
|
||||
status, body, _ = self.post(self.report())
|
||||
self.assertEqual(status, 502)
|
||||
self.assertIn("check the issue list", body["error"])
|
||||
|
||||
def test_title_is_cut(self):
|
||||
title = relay.issue_title({"text": "\n\n" + "w" * 300})
|
||||
self.assertEqual(len(title), relay.MAX_TITLE_CHARS)
|
||||
self.assertTrue(title.endswith("..."))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user