6f37120dc4
A paper needs its experiment figures, and a figure is not text: the bytes go to
MinIO and the sentence keeps a Markdown address. That is what keeps a sentence
one editable string — a picture moves between paragraphs by being cut and
pasted, and survives a template switch with the sentence it belongs to.
Three decisions carry the safety, and each is a way to serve something other
than what was uploaded:
* the key is the digest of the bytes, so uploading the same screenshot twice is
one object and the address can never come to mean a different picture — which
is what makes the year-long `immutable` cache header safe;
* the format is sniffed from the magic bytes, not read from the client's
`Content-Type` or filename, and SVG is refused because an uploaded SVG served
from this origin is stored XSS;
* serving is restricted to the key space this application writes, so
`GET /api/images/{key}` cannot become a browser for the rest of the bucket.
Images are served through the API rather than from a public bucket URL so a
sentence never embeds a host name — the LAN in development and the public
address later would otherwise disagree — and the bucket can stay private. The
object is streamed rather than read into memory, and the connection is released
when the reader stops.
Storage unconfigured is a 503 that names the missing variables, not a crash:
the writing path does not depend on the bucket.
`scripts/smoke_images.py` walks the whole thing: each accepted format, the
refusals (text, SVG, a mislabelled file, an empty file, a key we did not
write), and a sentence that carries a figure through the paper endpoints.
105 lines
3.6 KiB
Python
105 lines
3.6 KiB
Python
"""Application settings, loaded from ``backend/.env`` and the environment.
|
|
|
|
The database URL is assembled with :func:`sqlalchemy.engine.URL.create` rather
|
|
than string formatting. That matters here: the TiDB password contains ``@``,
|
|
and interpolating it into a DSN by hand silently truncates the password at the
|
|
first ``@`` (it gets parsed as the user/host separator). ``URL.create``
|
|
percent-encodes each component correctly.
|
|
"""
|
|
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from typing import Union
|
|
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
from sqlalchemy import URL
|
|
|
|
# backend/app/core/config.py -> backend/
|
|
BASE_DIR = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
"""Runtime configuration for the API service."""
|
|
|
|
model_config = SettingsConfigDict(
|
|
env_file=BASE_DIR / ".env",
|
|
env_file_encoding="utf-8",
|
|
extra="ignore",
|
|
)
|
|
|
|
app_name: str = "paper-doc API"
|
|
api_prefix: str = "/api"
|
|
debug: bool = True
|
|
|
|
# The Vite dev server proxies /api to this service, so CORS is normally not
|
|
# exercised during development; it is configured for direct-origin setups.
|
|
cors_origins: list[str] = [
|
|
"http://127.0.0.1:5173",
|
|
"http://localhost:5173",
|
|
]
|
|
|
|
# --- Database (TiDB) -------------------------------------------------
|
|
db_host: str = "127.0.0.1"
|
|
db_port: int = 4000
|
|
db_user: str = "root"
|
|
db_password: str = ""
|
|
db_name: str = "paper_doc"
|
|
|
|
# When set, this wins over the DB_* parts above and is used verbatim.
|
|
database_url: str | None = None
|
|
|
|
# --- Connection pool -------------------------------------------------
|
|
db_echo: bool = False
|
|
db_pool_pre_ping: bool = True
|
|
db_pool_recycle: int = 3600
|
|
|
|
# --- Object storage (MinIO) ------------------------------------------
|
|
#
|
|
# Where the images a paper embeds are kept. Empty by default rather than
|
|
# pointed at a plausible host: a wrong-but-set address fails as a timeout
|
|
# deep inside boto3, while an empty one fails immediately and says which
|
|
# variables are missing. The bucket is created on first upload if it is not
|
|
# there, so a fresh deployment needs the credentials and nothing else.
|
|
minio_endpoint: str = ""
|
|
minio_access_key: str = ""
|
|
minio_secret_key: str = ""
|
|
minio_bucket: str = "paper-images"
|
|
minio_region: str = "us-east-1"
|
|
|
|
#: Largest image accepted, in bytes. An experiment figure is a few hundred
|
|
#: kilobytes; the ceiling is here to stop a mistake (a raw TIFF, a video)
|
|
#: from filling the bucket, not to be hit in normal use.
|
|
max_image_bytes: int = 20 * 1024 * 1024
|
|
|
|
@property
|
|
def sqlalchemy_url(self) -> Union[URL, str]:
|
|
"""The SQLAlchemy connection URL.
|
|
|
|
Returns a :class:`~sqlalchemy.engine.URL` unless ``DATABASE_URL`` was
|
|
supplied explicitly, in which case that string is passed through.
|
|
"""
|
|
if self.database_url:
|
|
return self.database_url
|
|
return URL.create(
|
|
drivername="mysql+pymysql",
|
|
username=self.db_user,
|
|
password=self.db_password,
|
|
host=self.db_host,
|
|
port=self.db_port,
|
|
database=self.db_name,
|
|
)
|
|
|
|
@property
|
|
def safe_database_url(self) -> str:
|
|
"""The URL rendered with the password masked, for logs and diagnostics."""
|
|
url = self.sqlalchemy_url
|
|
if isinstance(url, str):
|
|
return URL.make_url(url).render_as_string(hide_password=True)
|
|
return url.render_as_string(hide_password=True)
|
|
|
|
|
|
@lru_cache
|
|
def get_settings() -> Settings:
|
|
"""Return the process-wide settings singleton."""
|
|
return Settings()
|