154 lines
5.2 KiB
Python
154 lines
5.2 KiB
Python
"""Single-origin, bounded Bot API transport. Never expose response diagnostics."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from http import HTTPStatus
|
|
from typing import TYPE_CHECKING, Final, Self, final
|
|
from urllib.parse import urlsplit
|
|
|
|
import httpx
|
|
|
|
from models import (
|
|
CATALOG_BYTES,
|
|
DOWNLOAD_BYTES,
|
|
TOTAL_BYTES,
|
|
FailureReason,
|
|
ImportFailureError,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
from types import TracebackType
|
|
|
|
TOKEN: Final = re.compile(r"[0-9]{1,20}:[A-Za-z0-9_-]{20,128}")
|
|
NAME: Final = re.compile(r"[A-Za-z0-9_]{1,64}")
|
|
FILE_PATH: Final = re.compile(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+")
|
|
TOKEN_BYTES: Final = 256
|
|
REQUEST_SECONDS: Final = 30
|
|
|
|
|
|
def pack_name(value: str) -> str:
|
|
"""Accept only short names or credential-free Telegram addstickers links."""
|
|
if NAME.fullmatch(value):
|
|
return value
|
|
parsed = urlsplit(value)
|
|
if (
|
|
parsed.scheme == "https"
|
|
and parsed.netloc in {"t.me", "telegram.me"}
|
|
and not parsed.query
|
|
and not parsed.fragment
|
|
and parsed.path.startswith("/addstickers/")
|
|
):
|
|
name = parsed.path.removeprefix("/addstickers/")
|
|
if NAME.fullmatch(name):
|
|
return name
|
|
raise ImportFailureError(FailureReason.INVALID_PACK_REFERENCE)
|
|
|
|
|
|
def api_origin(value: str) -> str:
|
|
"""Require one credential-free origin, allowing HTTP only on loopback."""
|
|
parsed = urlsplit(value)
|
|
if (
|
|
parsed.username is not None
|
|
or parsed.password is not None
|
|
or not parsed.hostname
|
|
or parsed.path not in {"", "/"}
|
|
or parsed.query
|
|
or parsed.fragment
|
|
or parsed.scheme not in {"https", "http"}
|
|
):
|
|
raise ImportFailureError(FailureReason.INVALID_API_ORIGIN)
|
|
if parsed.scheme == "http" and parsed.hostname not in {
|
|
"localhost",
|
|
"127.0.0.1",
|
|
"::1",
|
|
}:
|
|
raise ImportFailureError(FailureReason.INSECURE_API_ORIGIN)
|
|
# Force port validation before any credential is used.
|
|
_ = parsed.port
|
|
return value.rstrip("/")
|
|
|
|
|
|
def read_token(path: Path) -> str:
|
|
"""Read one bounded, syntactically valid credential from an explicit file."""
|
|
with path.open("rb") as source:
|
|
raw = source.read(TOKEN_BYTES + 1)
|
|
if len(raw) > TOKEN_BYTES:
|
|
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
|
token = raw.decode("ascii").strip()
|
|
if TOKEN.fullmatch(token) is None:
|
|
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
|
return token
|
|
|
|
|
|
@final
|
|
class Telegram:
|
|
"""Mutable byte accounting belongs to one sequential import."""
|
|
|
|
def __init__(self, origin: str, token: str) -> None:
|
|
"""Own a sequential transport without redirects or environment trust."""
|
|
self.origin = api_origin(origin)
|
|
self.token = token
|
|
self.total = 0
|
|
self.client = httpx.Client(
|
|
timeout=httpx.Timeout(10, connect=5),
|
|
limits=httpx.Limits(max_connections=1, max_keepalive_connections=1),
|
|
follow_redirects=False,
|
|
trust_env=False,
|
|
headers={"Accept-Encoding": "identity"},
|
|
)
|
|
|
|
def __enter__(self) -> Self:
|
|
"""Return this import's transport."""
|
|
return self
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: type[BaseException] | None,
|
|
exc: BaseException | None,
|
|
traceback: TracebackType | None,
|
|
) -> None:
|
|
"""Close the transport after success or failure."""
|
|
self.client.close()
|
|
|
|
def request(self, suffix: str, limit: int) -> bytes:
|
|
"""Bound raw response bytes, total transfer bytes and elapsed time."""
|
|
start = time.monotonic()
|
|
chunks: list[bytes] = []
|
|
size = 0
|
|
with self.client.stream("GET", self.origin + suffix) as response:
|
|
if (
|
|
response.status_code != HTTPStatus.OK
|
|
or response.headers.get("content-encoding", "identity") != "identity"
|
|
):
|
|
raise ImportFailureError(FailureReason.BOT_API_REQUEST_REJECTED)
|
|
for chunk in response.iter_raw():
|
|
size += len(chunk)
|
|
self.total += len(chunk)
|
|
if (
|
|
size > limit
|
|
or self.total > TOTAL_BYTES
|
|
or time.monotonic() - start > REQUEST_SECONDS
|
|
):
|
|
raise ImportFailureError(
|
|
FailureReason.DOWNLOAD_SIZE_OR_TIME_LIMIT_EXCEEDED
|
|
)
|
|
chunks.append(chunk)
|
|
return b"".join(chunks)
|
|
|
|
def method(self, method: str, parameter: str, value: str) -> bytes:
|
|
"""Encode method parameters as query data on the configured origin."""
|
|
# Values are encoded as query data, never interpreted as a URL/path.
|
|
query = str(httpx.QueryParams({parameter: value}))
|
|
return self.request(f"/bot{self.token}/{method}?{query}", CATALOG_BYTES)
|
|
|
|
def download(self, path: str) -> bytes:
|
|
"""Fetch a bounded file only after rejecting traversal and URL syntax."""
|
|
if FILE_PATH.fullmatch(path) is None or any(
|
|
p in {".", ".."} for p in path.split("/")
|
|
):
|
|
raise ImportFailureError(FailureReason.UNSAFE_BOT_API_FILE_PATH)
|
|
return self.request(f"/file/bot{self.token}/{path}", DOWNLOAD_BYTES)
|