feat: serve Belki images through private MinIO
This commit is contained in:
1 parent
b45e4925a6
commit
ecc1f696da
14 files changed
+194
-119
No files matched your search
+7
-2
@@ -11,8 +11,13 @@ SUDOKU_DB=data/sudoku.sqlite3
|
|||||||
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
||||||
# Required to access /admin and /api/admin/calculations.
|
# Required to access /admin and /api/admin/calculations.
|
||||||
BELKI_ADMIN_PASSWORD=change-me
|
BELKI_ADMIN_PASSWORD=change-me
|
||||||
# Optional image-hosting-web API origin, e.g. https://nyan.nyan404.ru.
|
# Private MinIO is never exposed publicly; the app serves URLs through this origin.
|
||||||
BELKI_IMAGE_HOST_API_URL=
|
BELKI_S3_ENDPOINTS=
|
||||||
|
BELKI_S3_ACCESS_KEY=
|
||||||
|
BELKI_S3_SECRET_KEY=
|
||||||
|
BELKI_S3_BUCKET=belki-images
|
||||||
|
BELKI_S3_SECURE=false
|
||||||
|
BELKI_IMAGE_PUBLIC_URL=http://localhost:8080
|
||||||
# Google Sheets export stays disabled until a Google Apps Script Web App endpoint is approved.
|
# Google Sheets export stays disabled until a Google Apps Script Web App endpoint is approved.
|
||||||
# When enabled, both created and accepted application events are delivered from the durable outbox.
|
# When enabled, both created and accepted application events are delivered from the durable outbox.
|
||||||
BELKI_GOOGLE_EXPORT_ENABLED=0
|
BELKI_GOOGLE_EXPORT_ENABLED=0
|
||||||
|
|||||||
+5
-1
@@ -5,6 +5,7 @@ stages:
|
|||||||
|
|
||||||
variables:
|
variables:
|
||||||
DOCKER_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed-clone/belki
|
DOCKER_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed-clone/belki
|
||||||
|
BELKI_BASE_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed-clone/belki-base
|
||||||
GATEWAY_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed
|
GATEWAY_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed
|
||||||
KUBE_NAMESPACE: belki
|
KUBE_NAMESPACE: belki
|
||||||
DOCKER_HOST: tcp://docker:2375
|
DOCKER_HOST: tcp://docker:2375
|
||||||
@@ -56,7 +57,10 @@ build:
|
|||||||
- echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin
|
- echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin
|
||||||
|
|
||||||
- export IMAGE_TAG="$CI_COMMIT_SHORT_SHA"
|
- export IMAGE_TAG="$CI_COMMIT_SHORT_SHA"
|
||||||
- docker build --platform linux/amd64 --pull -t "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$DOCKER_IMAGE_REPOSITORY:latest" .
|
- export BASE_IMAGE_TAG="py312-$IMAGE_TAG"
|
||||||
|
- docker build --platform linux/amd64 --pull -f Dockerfile.base -t "$BELKI_BASE_IMAGE_REPOSITORY:$BASE_IMAGE_TAG" .
|
||||||
|
- docker push "$BELKI_BASE_IMAGE_REPOSITORY:$BASE_IMAGE_TAG"
|
||||||
|
- docker build --platform linux/amd64 --pull --build-arg "BELKI_BASE_IMAGE=$BELKI_BASE_IMAGE_REPOSITORY:$BASE_IMAGE_TAG" -t "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$DOCKER_IMAGE_REPOSITORY:latest" .
|
||||||
- docker build --platform linux/amd64 --pull -f Dockerfile.gateway -t "$GATEWAY_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$GATEWAY_IMAGE_REPOSITORY:latest" .
|
- docker build --platform linux/amd64 --pull -f Dockerfile.gateway -t "$GATEWAY_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$GATEWAY_IMAGE_REPOSITORY:latest" .
|
||||||
- docker push "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG"
|
- docker push "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||||
- docker push "$DOCKER_IMAGE_REPOSITORY:latest"
|
- docker push "$DOCKER_IMAGE_REPOSITORY:latest"
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
||||||
- The build job waits for the DinD daemon and runs `docker info` before building.
|
- The build job waits for the DinD daemon and runs `docker info` before building.
|
||||||
- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig.
|
- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig.
|
||||||
|
- Private image storage is the separate Kubernetes Secret `belki-image-store`, not the CI-recreated `belki-runtime`. It contains only the internal MinIO endpoints and bucket-scoped credentials; keep MinIO private and preserve the `/api/images/<id>` Belki proxy when changing upload flows.
|
||||||
|
|
||||||
## Agent Rules
|
## Agent Rules
|
||||||
- Zod `.describe()` on optional fields: always append `.optional()` — e.g. `zod.string().describe("…").optional()` — to avoid validation failures when the field is absent.
|
- Zod `.describe()` on optional fields: always append `.optional()` — e.g. `zod.string().describe("…").optional()` — to avoid validation failures when the field is absent.
|
||||||
|
|||||||
+5
-14
@@ -1,20 +1,11 @@
|
|||||||
# Production is deployed to amd64 nodes. Build dependencies from the official
|
# CI passes an immutable amd64 base tag after building Dockerfile.base. The
|
||||||
# base here because the previous private tag was published arm64-only.
|
# public base default keeps direct local Docker builds possible.
|
||||||
FROM --platform=linux/amd64 python:3.12-slim
|
ARG BELKI_BASE_IMAGE=python:3.12-slim
|
||||||
|
FROM --platform=linux/amd64 ${BELKI_BASE_IMAGE}
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
|
||||||
PYTHONUNBUFFERED=1 \
|
|
||||||
LANG=C.UTF-8 \
|
|
||||||
LC_ALL=C.UTF-8
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
COPY requirements.txt ./requirements.txt
|
|
||||||
RUN python -m pip install --no-cache-dir --upgrade "pip==26.2.1" \
|
|
||||||
&& python -m pip install --no-cache-dir -r requirements.txt
|
|
||||||
|
|
||||||
COPY app ./app
|
COPY app ./app
|
||||||
COPY web ./web
|
COPY web ./web
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
CMD ["python", "-m", "app.main"]
|
CMD ["python", "-m", "app.main"]
|
||||||
#+ Runtime image intentionally reuses the immutable Python dependency base; only application sources are copied here.
|
#+ Runtime image reuses the immutable Python dependency base; only application sources are copied here.
|
||||||
@@ -74,3 +74,7 @@ The final gateway Dockerfile must copy `nginx.conf` into the release image, not
|
|||||||
# 2026-09-06: VK conversation scheduler
|
# 2026-09-06: VK conversation scheduler
|
||||||
|
|
||||||
`app/belki/vk_scheduler.py` хранит реестр бесед, шаблоны, расписания и историю попыток в общей БД (`BELKI_DATABASE_URL` или `BELKI_HISTORY_DB`). `BelkiBot` регистрирует `chat_invite_user`/`chat_invite_user_by_link`, помечает `chat_kick_user`/`chat_leave_user` как недоступные и запускает idempotent scheduler в отдельном daemon-потоке. Админские endpoints `/api/admin/vk/conversations`, `/templates`, `/schedules` защищены существующей сессией; сообщения по умолчанию выключены.
|
`app/belki/vk_scheduler.py` хранит реестр бесед, шаблоны, расписания и историю попыток в общей БД (`BELKI_DATABASE_URL` или `BELKI_HISTORY_DB`). `BelkiBot` регистрирует `chat_invite_user`/`chat_invite_user_by_link`, помечает `chat_kick_user`/`chat_leave_user` как недоступные и запускает idempotent scheduler в отдельном daemon-потоке. Админские endpoints `/api/admin/vk/conversations`, `/templates`, `/schedules` защищены существующей сессией; сообщения по умолчанию выключены.
|
||||||
|
|
||||||
|
# 2026-09-08: private MinIO image storage
|
||||||
|
|
||||||
|
`app/belki/image_host.py` now uses private distributed MinIO rather than `nyan.nyan404.ru`. The five internal S3 endpoints are tried in order for each operation; uploads are stored under an unguessable 128-bit object ID and public URLs resolve only through `https://cat.nyan404.ru/api/images/<id>`. Keep the MinIO bucket private. `belki-image-store` is a standalone out-of-band Secret with only `GetObject`/`PutObject` for `belki-images`; never merge it into CI-recreated `belki-runtime` or commit credentials. Existing legacy img.nyan404.ru URLs remain stored as historical links and cannot be recovered by this change.
|
||||||
@@ -37,7 +37,7 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
||||||
|
|
||||||
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их через API `https://nyan.nyan404.ru` и сохраняет ссылки вместе с отчётом. Пользовательский интерфейс image-host доступен на `https://img.nyan404.ru`. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же API. Google Sheets пока не подключён.
|
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер сохраняет их в приватном S3-совместимом MinIO и возвращает ссылку на собственный маршрут `/api/images/<id>`. Поэтому MinIO не открывается в интернет, а пользователи получают изображение через контейнер Belki. Настройки `BELKI_S3_*` и отдельный Secret `belki-image-store` задаются вне репозитория. Google Sheets пока не подключён.
|
||||||
|
|
||||||
## Судоку
|
## Судоку
|
||||||
|
|
||||||
|
|||||||
+66
-68
@@ -1,14 +1,14 @@
|
|||||||
"""
|
"""Private MinIO-backed storage for report screenshots and VK attachments."""
|
||||||
Клиент для зеркалирования фотографий из VK на external image-host.
|
|
||||||
|
|
||||||
Используется для хранения скриншотов-приложений к отчётам.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
from collections.abc import Iterator
|
||||||
|
from io import BytesIO
|
||||||
import os
|
import os
|
||||||
from urllib.request import Request, urlopen
|
import secrets
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
|
from minio import Minio
|
||||||
|
|
||||||
|
|
||||||
class ImageHostError(RuntimeError):
|
class ImageHostError(RuntimeError):
|
||||||
@@ -29,23 +29,32 @@ def detect_raster_image_type(body: bytes) -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
class ImageHostClient:
|
class ImageStoreClient:
|
||||||
"""
|
"""Stores images in private MinIO and returns URLs served by Belki itself."""
|
||||||
Клиент для mirror VK-фото на external image-host.
|
|
||||||
|
|
||||||
Использует API image-hosting-web (initiate upload → PUT file → get URL).
|
def __init__(self, endpoints: str | None = None, access_key: str | None = None,
|
||||||
"""
|
secret_key: str | None = None, bucket: str | None = None,
|
||||||
def __init__(self, api_url: str | None = None, retention: str = "forever", timeout: int = 30) -> None:
|
public_url: str | None = None, secure: bool | None = None, timeout: int = 30) -> None:
|
||||||
"""
|
raw_endpoints = endpoints if endpoints is not None else os.getenv("BELKI_S3_ENDPOINTS", "")
|
||||||
Args:
|
self.endpoints = tuple(item.strip().removeprefix("http://").removeprefix("https://") for item in raw_endpoints.split(",") if item.strip())
|
||||||
api_url: URL API image-host (из BELKI_IMAGE_HOST_API_URL)
|
self.access_key = access_key if access_key is not None else os.getenv("BELKI_S3_ACCESS_KEY", "")
|
||||||
retention: Политика хранения (по умолчанию "forever")
|
self.secret_key = secret_key if secret_key is not None else os.getenv("BELKI_S3_SECRET_KEY", "")
|
||||||
timeout: Таймаут HTTP-запросов в секундах
|
self.bucket = bucket if bucket is not None else os.getenv("BELKI_S3_BUCKET", "belki-images")
|
||||||
"""
|
self.public_url = (public_url if public_url is not None else os.getenv("BELKI_IMAGE_PUBLIC_URL", "")).rstrip("/")
|
||||||
self.api_url = (api_url or os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).rstrip("/")
|
self.secure = secure if secure is not None else os.getenv("BELKI_S3_SECURE", "false").lower() == "true"
|
||||||
self.retention = retention
|
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
|
|
||||||
|
def _clients(self) -> Iterator[Minio]:
|
||||||
|
if not self.endpoints or not self.access_key or not self.secret_key:
|
||||||
|
raise ImageHostError("image storage is not configured")
|
||||||
|
for endpoint in self.endpoints:
|
||||||
|
yield Minio(endpoint, access_key=self.access_key, secret_key=self.secret_key, secure=self.secure)
|
||||||
|
|
||||||
|
def _public_url(self, object_name: str) -> str:
|
||||||
|
if not self.public_url:
|
||||||
|
raise ImageHostError("image public URL is not configured")
|
||||||
|
return f"{self.public_url}/api/images/{object_name}"
|
||||||
|
|
||||||
def mirror(self, photo: dict[str, object]) -> str | None:
|
def mirror(self, photo: dict[str, object]) -> str | None:
|
||||||
"""
|
"""
|
||||||
Зеркалирует одну VK-фотографию на image-host.
|
Зеркалирует одну VK-фотографию на image-host.
|
||||||
@@ -62,7 +71,7 @@ class ImageHostClient:
|
|||||||
Returns:
|
Returns:
|
||||||
Прямая ссылка на загруженное фото или None
|
Прямая ссылка на загруженное фото или None
|
||||||
"""
|
"""
|
||||||
if not self.api_url or not photo.get("url"):
|
if not photo.get("url"):
|
||||||
return None
|
return None
|
||||||
source_url = str(photo["url"])
|
source_url = str(photo["url"])
|
||||||
with urlopen(source_url, timeout=self.timeout) as response:
|
with urlopen(source_url, timeout=self.timeout) as response:
|
||||||
@@ -84,56 +93,45 @@ class ImageHostClient:
|
|||||||
return self.upload_bytes(body, file_name, content_type)
|
return self.upload_bytes(body, file_name, content_type)
|
||||||
|
|
||||||
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
||||||
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
|
"""Stores bytes privately and returns the public Belki-proxy URL."""
|
||||||
if not self.api_url or not body:
|
if not body:
|
||||||
return None
|
return None
|
||||||
|
content_type = detect_raster_image_type(body)
|
||||||
|
if content_type is None:
|
||||||
|
raise ImageHostError("only PNG, JPEG, and WebP images are supported")
|
||||||
|
suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}.get(content_type)
|
||||||
|
if suffix is None:
|
||||||
|
raise ImageHostError("only PNG, JPEG, and WebP images are supported")
|
||||||
|
object_name = f"{secrets.token_hex(16)}.{suffix}"
|
||||||
|
last_error: Exception | None = None
|
||||||
try:
|
try:
|
||||||
initiate = self._request_json(
|
for client in self._clients():
|
||||||
"/api/uploads/initiate",
|
try:
|
||||||
{
|
client.put_object(self.bucket, object_name, BytesIO(body), len(body), content_type=content_type)
|
||||||
"retention": self.retention,
|
return self._public_url(object_name)
|
||||||
"files": [{"name": file_name, "size": len(body), "type": content_type}],
|
except Exception as exc:
|
||||||
},
|
last_error = exc
|
||||||
)
|
|
||||||
files = initiate.get("files") or []
|
|
||||||
if not files or not files[0].get("uploadUrl"):
|
|
||||||
raise ImageHostError("image host did not return an upload URL")
|
|
||||||
upload = files[0]
|
|
||||||
request = Request(
|
|
||||||
str(upload["uploadUrl"]),
|
|
||||||
data=body,
|
|
||||||
method="PUT",
|
|
||||||
headers={str(key): str(value) for key, value in (upload.get("uploadHeaders") or {}).items()},
|
|
||||||
)
|
|
||||||
with urlopen(request, timeout=self.timeout):
|
|
||||||
pass
|
|
||||||
return str(upload.get("directUrl") or upload.get("cdnUrl") or "") or None
|
|
||||||
except ImageHostError:
|
except ImageHostError:
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
if last_error is not None:
|
||||||
raise ImageHostError(f"image host upload failed: {exc}") from exc
|
raise ImageHostError(f"image storage upload failed: {last_error}") from last_error
|
||||||
|
raise ImageHostError("image storage has no reachable endpoints")
|
||||||
|
|
||||||
def _request_json(self, path: str, payload: dict[str, object]) -> dict[str, object]:
|
def get_object(self, object_name: str):
|
||||||
"""
|
"""Returns an object response from the first healthy MinIO endpoint."""
|
||||||
Выполняет POST-запрос к API image-host и возвращает JSON-ответ.
|
last_error: Exception | None = None
|
||||||
|
|
||||||
В случае ошибки обёртывает исключение в ImageHostError.
|
|
||||||
"""
|
|
||||||
request = Request(
|
|
||||||
f"{self.api_url}{path}",
|
|
||||||
data=json.dumps(payload).encode("utf-8"),
|
|
||||||
method="POST",
|
|
||||||
headers={
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Accept": "application/json",
|
|
||||||
"User-Agent": "BelkiCalculator/1.0 (+https://cat.nyan404.ru/belki)",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
with urlopen(request, timeout=self.timeout) as response:
|
for client in self._clients():
|
||||||
result = json.load(response)
|
try:
|
||||||
|
return client.get_object(self.bucket, object_name)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise ImageHostError(f"image host initiate failed: {exc}") from exc
|
last_error = exc
|
||||||
if not isinstance(result, dict):
|
except ImageHostError:
|
||||||
raise ImageHostError("image host returned an invalid response")
|
raise
|
||||||
return result
|
if last_error is not None:
|
||||||
|
raise ImageHostError(f"image storage read failed: {last_error}") from last_error
|
||||||
|
raise ImageHostError("image storage has no reachable endpoints")
|
||||||
|
|
||||||
|
|
||||||
|
# Kept as an import-compatible name for existing VK integration code.
|
||||||
|
ImageHostClient = ImageStoreClient
|
||||||
+30
-2
@@ -5,6 +5,7 @@ import base64
|
|||||||
import hashlib
|
import hashlib
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
@@ -19,7 +20,7 @@ from .belki.applications import ApplicationError, ApplicationStore, validate_app
|
|||||||
from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds
|
from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds
|
||||||
from .belki.google_sheets_export import GoogleSheetsExportService
|
from .belki.google_sheets_export import GoogleSheetsExportService
|
||||||
from .belki.identity import IdentityDirectory
|
from .belki.identity import IdentityDirectory
|
||||||
from .belki.image_host import ImageHostClient, ImageHostError
|
from .belki.image_host import ImageHostError, ImageStoreClient
|
||||||
from .belki.xlsx_export import build_xlsx
|
from .belki.xlsx_export import build_xlsx
|
||||||
from .sudoku import SudokuError, SudokuStore
|
from .sudoku import SudokuError, SudokuStore
|
||||||
from .belki.vk_scheduler import VkConversationStore
|
from .belki.vk_scheduler import VkConversationStore
|
||||||
@@ -48,6 +49,7 @@ MAX_ADMIN_AUTH_ATTEMPTS = 5
|
|||||||
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
||||||
WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60
|
WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60
|
||||||
MAX_ISSUED_WEB_UPLOAD_URLS = 1_000
|
MAX_ISSUED_WEB_UPLOAD_URLS = 1_000
|
||||||
|
IMAGE_OBJECT_NAME = re.compile(r"^[a-f0-9]{32}\.(?:png|jpg|webp)$")
|
||||||
ADMIN_SESSION_TTL_SECONDS = 12 * 60 * 60
|
ADMIN_SESSION_TTL_SECONDS = 12 * 60 * 60
|
||||||
MAX_ADMIN_SESSIONS = 100
|
MAX_ADMIN_SESSIONS = 100
|
||||||
|
|
||||||
@@ -401,6 +403,32 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if path == "/api/admin/updates":
|
if path == "/api/admin/updates":
|
||||||
self._serve_admin_updates()
|
self._serve_admin_updates()
|
||||||
return
|
return
|
||||||
|
if path.startswith("/api/images/"):
|
||||||
|
object_name = path.removeprefix("/api/images/")
|
||||||
|
if not IMAGE_OBJECT_NAME.fullmatch(object_name):
|
||||||
|
self._json(404, {"error": "Не найдено"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
response = ImageStoreClient().get_object(object_name)
|
||||||
|
except ImageHostError:
|
||||||
|
self._json(404, {"error": "Не найдено"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", response.headers.get("Content-Type", mimetypes.guess_type(object_name)[0] or "application/octet-stream"))
|
||||||
|
content_length = response.headers.get("Content-Length")
|
||||||
|
if content_length:
|
||||||
|
self.send_header("Content-Length", content_length)
|
||||||
|
self.send_header("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
self.end_headers()
|
||||||
|
while chunk := response.read(64 * 1024):
|
||||||
|
self.wfile.write(chunk)
|
||||||
|
except (BrokenPipeError, ConnectionError, OSError):
|
||||||
|
return
|
||||||
|
finally:
|
||||||
|
response.close()
|
||||||
|
response.release_conn()
|
||||||
|
return
|
||||||
if path == "/api/admin/calculations":
|
if path == "/api/admin/calculations":
|
||||||
if not self._admin_authorized():
|
if not self._admin_authorized():
|
||||||
return
|
return
|
||||||
@@ -548,7 +576,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if declared_type and declared_type != content_type:
|
if declared_type and declared_type != content_type:
|
||||||
raise ApiError("Тип файла не совпадает с содержимым изображения")
|
raise ApiError("Тип файла не совпадает с содержимым изображения")
|
||||||
try:
|
try:
|
||||||
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).upload_bytes(
|
url = ImageStoreClient().upload_bytes(
|
||||||
body, safe_upload_name(payload.get("name"), content_type), content_type
|
body, safe_upload_name(payload.get("name"), content_type), content_type
|
||||||
)
|
)
|
||||||
except ImageHostError as exc:
|
except ImageHostError as exc:
|
||||||
|
|||||||
@@ -123,8 +123,18 @@ spec:
|
|||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
name: belki-runtime
|
name: belki-runtime
|
||||||
key: BELKI_ADMIN_PASSWORD
|
key: BELKI_ADMIN_PASSWORD
|
||||||
- name: BELKI_IMAGE_HOST_API_URL
|
- name: BELKI_S3_ENDPOINTS
|
||||||
value: https://nyan.nyan404.ru
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_ENDPOINTS}}
|
||||||
|
- name: BELKI_S3_ACCESS_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_ACCESS_KEY}}
|
||||||
|
- name: BELKI_S3_SECRET_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_SECRET_KEY}}
|
||||||
|
- name: BELKI_S3_BUCKET
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_BUCKET}}
|
||||||
|
- name: BELKI_IMAGE_PUBLIC_URL
|
||||||
|
value: https://cat.nyan404.ru
|
||||||
|
- name: BELKI_S3_SECURE
|
||||||
|
value: "false"
|
||||||
readinessProbe:
|
readinessProbe:
|
||||||
httpGet:
|
httpGet:
|
||||||
path: /health
|
path: /health
|
||||||
@@ -204,6 +214,16 @@ spec:
|
|||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
name: belki-runtime
|
name: belki-runtime
|
||||||
key: BELKI_DATABASE_URL
|
key: BELKI_DATABASE_URL
|
||||||
- name: BELKI_IMAGE_HOST_API_URL
|
- name: BELKI_S3_ENDPOINTS
|
||||||
value: https://nyan.nyan404.ru
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_ENDPOINTS}}
|
||||||
|
- name: BELKI_S3_ACCESS_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_ACCESS_KEY}}
|
||||||
|
- name: BELKI_S3_SECRET_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_SECRET_KEY}}
|
||||||
|
- name: BELKI_S3_BUCKET
|
||||||
|
valueFrom: {secretKeyRef: {name: belki-image-store, key: BELKI_S3_BUCKET}}
|
||||||
|
- name: BELKI_IMAGE_PUBLIC_URL
|
||||||
|
value: https://cat.nyan404.ru
|
||||||
|
- name: BELKI_S3_SECURE
|
||||||
|
value: "false"
|
||||||
# production.yaml defines the production production resource; keep namespace and secret references aligned with belki.
|
# production.yaml defines the production production resource; keep namespace and secret references aligned with belki.
|
||||||
@@ -11,4 +11,17 @@ stringData:
|
|||||||
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
|
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
|
||||||
POSTGRES_PASSWORD: replace-out-of-band
|
POSTGRES_PASSWORD: replace-out-of-band
|
||||||
BELKI_ADMIN_PASSWORD: replace-out-of-band
|
BELKI_ADMIN_PASSWORD: replace-out-of-band
|
||||||
|
# Create separately as `belki-image-store`; do not add these values to CI-managed belki-runtime.
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: belki-image-store
|
||||||
|
namespace: belki
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
BELKI_S3_ENDPOINTS: 10.18.0.50:9000,10.18.0.51:9000,10.18.0.52:9000,10.18.0.53:9000,10.18.0.55:9000
|
||||||
|
BELKI_S3_ACCESS_KEY: replace-out-of-band
|
||||||
|
BELKI_S3_SECRET_KEY: replace-out-of-band
|
||||||
|
BELKI_S3_BUCKET: belki-images
|
||||||
# secret.example.yaml defines the secret.example production resource; keep namespace and secret references aligned with belki.
|
# secret.example.yaml defines the secret.example production resource; keep namespace and secret references aligned with belki.
|
||||||
+9
-5
@@ -66,9 +66,11 @@ mindmap
|
|||||||
export outbox
|
export outbox
|
||||||
identities and profiles
|
identities and profiles
|
||||||
SQLite local fallback
|
SQLite local fallback
|
||||||
Image host
|
Private MinIO image storage
|
||||||
API nyan.nyan404.ru
|
belki-images bucket
|
||||||
Viewer img.nyan404.ru
|
five internal S3 endpoints
|
||||||
|
bucket-scoped GetObject PutObject account
|
||||||
|
public proxy /api/images/id
|
||||||
Integrations
|
Integrations
|
||||||
VK API
|
VK API
|
||||||
Optional Google Sheets export (HTTPS only)
|
Optional Google Sheets export (HTTPS only)
|
||||||
@@ -113,9 +115,11 @@ flowchart LR
|
|||||||
Bot --> Domain
|
Bot --> Domain
|
||||||
Web --> Store[(PostgreSQL or SQLite)]
|
Web --> Store[(PostgreSQL or SQLite)]
|
||||||
Bot --> Store
|
Bot --> Store
|
||||||
Web --> ImageHost[Image-host API]
|
Web --> ImageStore[Private MinIO]
|
||||||
Web --> Sudoku[Sudoku game store]
|
Web --> Sudoku[Sudoku game store]
|
||||||
Bot --> ImageHost
|
Bot --> ImageStore
|
||||||
|
Browser -->|public image URL| Web
|
||||||
|
Web -->|bounded proxy read| ImageStore
|
||||||
Admin[Администратор] -->|session cookie| Web
|
Admin[Администратор] -->|session cookie| Web
|
||||||
Admin -->|same filters| XLSX[Отчёты и заявки XLSX]
|
Admin -->|same filters| XLSX[Отчёты и заявки XLSX]
|
||||||
Web -->|UTC instants to UTC+3 display| Admin
|
Web -->|UTC instants to UTC+3 display| Admin
|
||||||
|
|||||||
@@ -2,3 +2,5 @@
|
|||||||
psycopg[binary]==3.3.4
|
psycopg[binary]==3.3.4
|
||||||
# GPL-3.0-only Sudoku generator/solver, selected explicitly for /sudoku.
|
# GPL-3.0-only Sudoku generator/solver, selected explicitly for /sudoku.
|
||||||
dokusan==0.1.0
|
dokusan==0.1.0
|
||||||
|
# Private S3-compatible storage used by the Belki image proxy.
|
||||||
|
minio==7.2.20
|
||||||
@@ -20,6 +20,8 @@
|
|||||||
- [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules.
|
- [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules.
|
||||||
|
|
||||||
## Runtime / Deployment
|
## Runtime / Deployment
|
||||||
|
- 2026-09-08: report screenshots and VK attachment mirrors use private distributed MinIO through the `minio==7.2.20` SDK. `belki-image-store` is a separate, out-of-band Kubernetes Secret containing the five internal endpoints, a bucket-scoped `GetObject`/`PutObject` account, and `belki-images`; it is deliberately separate from CI-managed `belki-runtime` so normal deploys cannot remove it. `belki-web` and `belki-bot` return/retain `https://cat.nyan404.ru/api/images/<128-bit-random-id>.<extension>` while `Handler` proxies reads from MinIO. MinIO has no public exposure.
|
||||||
|
- `Dockerfile.base` is rebuilt and pushed with the immutable `py312-<commit>` tag before the final Belki image; `Dockerfile` accepts that base through `BELKI_BASE_IMAGE`, leaving only application sources in the final layer.
|
||||||
- GitLab CI runs the build job.
|
- GitLab CI runs the build job.
|
||||||
- Production container architecture is explicitly `linux/amd64`: CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`, Dockerfiles pin the platform, and Kubernetes workloads select nodes labeled `kubernetes.io/arch: amd64`. The former private Python base tag was arm64-only and is no longer used by the application image.
|
- Production container architecture is explicitly `linux/amd64`: CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`, Dockerfiles pin the platform, and Kubernetes workloads select nodes labeled `kubernetes.io/arch: amd64`. The former private Python base tag was arm64-only and is no longer used by the application image.
|
||||||
- The job targets GitLab runner tag `fast` and builds through a privileged `docker:29.6.1-dind` service at `DOCKER_HOST=tcp://docker:2375`, with an explicit `alias: docker` and `DOCKER_TLS_CERTDIR=""`.
|
- The job targets GitLab runner tag `fast` and builds through a privileged `docker:29.6.1-dind` service at `DOCKER_HOST=tcp://docker:2375`, with an explicit `alias: docker` and `DOCKER_TLS_CERTDIR=""`.
|
||||||
|
|||||||
+25
-22
@@ -1,7 +1,7 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError, detect_raster_image_type as detect_mirrored_image_type
|
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError, ImageStoreClient, detect_raster_image_type as detect_mirrored_image_type
|
||||||
from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES,
|
from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES,
|
||||||
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
||||||
_ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt,
|
_ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt,
|
||||||
@@ -89,29 +89,32 @@ class ImageHostClientTests(unittest.TestCase):
|
|||||||
if slot:
|
if slot:
|
||||||
release_admin_update_slot()
|
release_admin_update_slot()
|
||||||
|
|
||||||
def test_default_client_targets_belki_image_host(self) -> None:
|
def test_default_client_requires_private_storage_settings(self) -> None:
|
||||||
with patch.dict("os.environ", {}, clear=True):
|
with patch.dict("os.environ", {}, clear=True):
|
||||||
self.assertEqual(ImageHostClient().api_url, "https://nyan.nyan404.ru")
|
with self.assertRaisesRegex(ImageHostError, "not configured"):
|
||||||
|
next(ImageStoreClient()._clients())
|
||||||
|
|
||||||
def test_initiate_identifies_the_belki_client(self) -> None:
|
def test_upload_uses_private_storage_and_returns_belki_url(self) -> None:
|
||||||
client = ImageHostClient(api_url="https://api.example.test")
|
client = ImageStoreClient(endpoints="minio-a:9000", access_key="access", secret_key="secret", bucket="belki-images", public_url="https://cat.example.test")
|
||||||
response = MagicMock()
|
minio = MagicMock()
|
||||||
response.__enter__.return_value = response
|
with patch.object(client, "_clients", return_value=iter([minio])):
|
||||||
with patch("app.belki.image_host.urlopen", return_value=response) as urlopen:
|
url = client.upload_bytes(b"\x89PNG\r\n\x1a\nimage", "screenshot.png", "image/png")
|
||||||
with patch("app.belki.image_host.json.load", return_value={"files": []}):
|
self.assertRegex(str(url), r"^https://cat\.example\.test/api/images/[a-f0-9]{32}\.png$")
|
||||||
client._request_json("/api/uploads/initiate", {"files": []})
|
minio.put_object.assert_called_once()
|
||||||
request = urlopen.call_args.args[0]
|
self.assertEqual(minio.put_object.call_args.args[:2], ("belki-images", str(url).rsplit("/", 1)[1]))
|
||||||
self.assertEqual(request.get_header("User-agent"), "BelkiCalculator/1.0 (+https://cat.nyan404.ru/belki)")
|
|
||||||
|
|
||||||
def test_upload_wraps_presigned_put_failure(self) -> None:
|
def test_upload_fails_over_to_another_minio_node(self) -> None:
|
||||||
client = ImageHostClient(api_url="https://api.example.test")
|
client = ImageStoreClient(endpoints="minio-a:9000,minio-b:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test")
|
||||||
with patch.object(client, "_request_json", return_value={"files": [{"uploadUrl": "https://storage.example.test/upload"}]}):
|
unavailable, healthy = MagicMock(), MagicMock()
|
||||||
with patch("app.belki.image_host.urlopen", side_effect=OSError("network unavailable")):
|
unavailable.put_object.side_effect = OSError("network unavailable")
|
||||||
with self.assertRaisesRegex(ImageHostError, "image host upload failed"):
|
with patch.object(client, "_clients", return_value=iter([unavailable, healthy])):
|
||||||
client.upload_bytes(b"image", "screenshot.jpg")
|
url = client.upload_bytes(b"\xff\xd8\xffimage", "screenshot.jpg")
|
||||||
|
self.assertTrue(str(url).endswith(".jpg"))
|
||||||
|
unavailable.put_object.assert_called_once()
|
||||||
|
healthy.put_object.assert_called_once()
|
||||||
|
|
||||||
def test_mirror_stops_before_reading_an_oversized_vk_image(self) -> None:
|
def test_mirror_stops_before_reading_an_oversized_vk_image(self) -> None:
|
||||||
client = ImageHostClient(api_url="https://api.example.test")
|
client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test")
|
||||||
response = MagicMock()
|
response = MagicMock()
|
||||||
response.__enter__.return_value = response
|
response.__enter__.return_value = response
|
||||||
response.headers.get.side_effect = lambda name: str(MAX_MIRRORED_IMAGE_BYTES + 1) if name == "Content-Length" else None
|
response.headers.get.side_effect = lambda name: str(MAX_MIRRORED_IMAGE_BYTES + 1) if name == "Content-Length" else None
|
||||||
@@ -121,17 +124,17 @@ class ImageHostClientTests(unittest.TestCase):
|
|||||||
response.read.assert_not_called()
|
response.read.assert_not_called()
|
||||||
|
|
||||||
def test_mirror_reads_at_most_the_configured_limit_plus_sentinel(self) -> None:
|
def test_mirror_reads_at_most_the_configured_limit_plus_sentinel(self) -> None:
|
||||||
client = ImageHostClient(api_url="https://api.example.test")
|
client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test")
|
||||||
response = MagicMock()
|
response = MagicMock()
|
||||||
response.__enter__.return_value = response
|
response.__enter__.return_value = response
|
||||||
response.headers.get.return_value = None
|
response.headers.get.return_value = None
|
||||||
response.read.return_value = b"\x89PNG\r\n\x1a\nimage"
|
response.read.return_value = b"\x89PNG\r\n\x1a\nimage"
|
||||||
with patch("app.belki.image_host.urlopen", return_value=response), patch.object(client, "upload_bytes", return_value="https://img.example.test/a.jpg"):
|
with patch("app.belki.image_host.urlopen", return_value=response), patch.object(client, "upload_bytes", return_value="https://cat.example.test/api/images/a.jpg"):
|
||||||
client.mirror({"url": "https://vk.example.test/photo.jpg", "owner_id": 1, "id": 2})
|
client.mirror({"url": "https://vk.example.test/photo.jpg", "owner_id": 1, "id": 2})
|
||||||
response.read.assert_called_once_with(MAX_MIRRORED_IMAGE_BYTES + 1)
|
response.read.assert_called_once_with(MAX_MIRRORED_IMAGE_BYTES + 1)
|
||||||
|
|
||||||
def test_mirror_rejects_non_image_bytes_even_with_an_image_content_type(self) -> None:
|
def test_mirror_rejects_non_image_bytes_even_with_an_image_content_type(self) -> None:
|
||||||
client = ImageHostClient(api_url="https://api.example.test")
|
client = ImageHostClient(endpoints="minio:9000", access_key="access", secret_key="secret", public_url="https://cat.example.test")
|
||||||
response = MagicMock()
|
response = MagicMock()
|
||||||
response.__enter__.return_value = response
|
response.__enter__.return_value = response
|
||||||
response.headers.get.return_value = None
|
response.headers.get.return_value = None
|
||||||
|
|||||||
Reference in new issue
Block a user