Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef4249eebd | ||
|
|
111c120834 | ||
|
|
4b42bd6f48 | ||
|
|
ea3d57728f | ||
|
|
6d33e37d5c | ||
|
|
4f7cdffb69 | ||
|
|
deb37daa9d |
+16
-17
@@ -1,5 +1,20 @@
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
# main only: a branch is tested through its pull request (a push of many branches at once
|
||||
# must not flood the runners)
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch: # manual run: Actions -> CI -> Run workflow
|
||||
|
||||
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
|
||||
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
|
||||
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
|
||||
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -45,17 +60,6 @@ jobs:
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -120,11 +124,6 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
@@ -27,8 +27,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
|
||||
@@ -60,9 +60,10 @@ def _identity_is_ours() -> None:
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Every signed-in user may list users: the console needs names to render "assigned to"
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
_: AppUser = Depends(require_moderator)) -> list[dict]:
|
||||
"""This module's administration only. On the platform `app_user` is the whole shared roster —
|
||||
people who cannot open this module at all — with their addresses and tiers; Scribe has no
|
||||
picker that needs it, and the console reads it only on the administration screen."""
|
||||
# One query for the whole page's tier column, not one per row: `moderator_ids` returns this
|
||||
# module's roster as a set, and standalone it returns an empty set without touching the database.
|
||||
moderators = moderation_service.moderator_ids(db)
|
||||
|
||||
@@ -58,10 +58,16 @@ def placeholders(body: str) -> tuple[list[str], list[str]]:
|
||||
_AMOUNT_GROUPED = re.compile(r"^\d{1,3}(?:[ .]\d{3})+(?:,\d{1,2})?$")
|
||||
_AMOUNT_PLAIN = re.compile(r"^\d+(?:[.,]\d{1,2})?$")
|
||||
_CURRENCY = re.compile(r"\s*(?:zł|pln|złotych|złote|złoty)\.?\s*$", re.I)
|
||||
#: Longer than any amount the checks can say anything about ("999 999 999 999,99 złotych" is 26).
|
||||
#: Checked BEFORE `_CURRENCY`, whose leading `\s*` is tried at every position of the text: on a
|
||||
#: field value of up to 20 000 characters with whitespace inside, that search is quadratic.
|
||||
MAX_AMOUNT_TEXT = 64
|
||||
|
||||
|
||||
def parse_amount(raw: Any) -> Decimal | None:
|
||||
"""``"12 345,67"``, ``"12.345,67"``, ``"12345.67"``, ``"12345,67 zł"`` → Decimal; else None."""
|
||||
if len(str(raw or "")) > MAX_AMOUNT_TEXT:
|
||||
return None
|
||||
text = _CURRENCY.sub("", str(raw or "").replace(" ", " ").strip())
|
||||
if _AMOUNT_GROUPED.match(text):
|
||||
text = text.replace(" ", "").replace(".", "").replace(",", ".")
|
||||
|
||||
@@ -22,14 +22,19 @@ from ..config import get_settings
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
|
||||
|
||||
def _client(url: str, service: str) -> ModuleClient | None:
|
||||
#: Lexicon answers with JSON (a search page, or one source's library), never a file: well under
|
||||
#: core's 64 MiB default, which is Galena's per-file cap and stays Galena's.
|
||||
LEXICON_MAX_BODY = 16 * 1024 * 1024
|
||||
|
||||
|
||||
def _client(url: str, service: str, **kw: Any) -> ModuleClient | None:
|
||||
if not url:
|
||||
return None
|
||||
return ModuleClient(url, service=service, timeout=get_settings().module_call_timeout)
|
||||
return ModuleClient(url, service=service, timeout=get_settings().module_call_timeout, **kw)
|
||||
|
||||
|
||||
def lexicon() -> ModuleClient | None:
|
||||
return _client(get_settings().lexicon_url, "Lexicon")
|
||||
return _client(get_settings().lexicon_url, "Lexicon", max_body=LEXICON_MAX_BODY)
|
||||
|
||||
|
||||
def galena() -> ModuleClient | None:
|
||||
@@ -76,16 +81,37 @@ def search_clauses(token: str | None, q: str, page: int = 1) -> dict:
|
||||
"items": items}
|
||||
|
||||
|
||||
def fetch_clause(client: ModuleClient, token: str | None, source_id: Any, position: Any) -> dict:
|
||||
def _library(client: ModuleClient, token: str | None, sid: uuid.UUID,
|
||||
cache: dict | None) -> dict:
|
||||
"""One source's whole library. With `cache`, each source is asked for once per check — its
|
||||
answer, or its refusal — however many slots quote it."""
|
||||
if cache is not None and sid in cache:
|
||||
hit = cache[sid]
|
||||
if isinstance(hit, AppError):
|
||||
raise hit
|
||||
return hit
|
||||
try:
|
||||
answer = client.request("GET", f"/sources/{sid}/library", token=token)
|
||||
answer.raise_for_status(client.service, "Lexicon nie odpowiedział.")
|
||||
except AppError as exc:
|
||||
if cache is not None:
|
||||
cache[sid] = exc
|
||||
raise
|
||||
body = answer.json()
|
||||
if cache is not None:
|
||||
cache[sid] = body
|
||||
return body
|
||||
|
||||
|
||||
def fetch_clause(client: ModuleClient, token: str | None, source_id: Any, position: Any, *,
|
||||
cache: dict | None = None) -> dict:
|
||||
"""One clause's current text from its source (`GET /sources/{id}/library`)."""
|
||||
try:
|
||||
sid = uuid.UUID(str(source_id))
|
||||
pos = int(position)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("Niepoprawny adres klauzuli.", {"code": "clause_ref_invalid"}) from None
|
||||
answer = client.request("GET", f"/sources/{sid}/library", token=token)
|
||||
answer.raise_for_status(client.service, "Lexicon nie odpowiedział.")
|
||||
body = answer.json()
|
||||
body = _library(client, token, sid, cache)
|
||||
for clause in body.get("clauses") or []:
|
||||
if clause.get("position") == pos:
|
||||
return {"source_id": str(sid), "source_title": body.get("source_title"),
|
||||
@@ -105,11 +131,13 @@ def lexicon_lookup(token: str | None):
|
||||
client = lexicon()
|
||||
if client is None:
|
||||
return None
|
||||
libraries: dict = {} # one check: each source fetched once, not once per slot quoting it
|
||||
|
||||
def look(_slot: str, clause: dict) -> str | None:
|
||||
ref = clause.get("lexicon") or {}
|
||||
try:
|
||||
return fetch_clause(client, token, ref.get("source_id"), ref.get("position"))["text"]
|
||||
return fetch_clause(client, token, ref.get("source_id"), ref.get("position"),
|
||||
cache=libraries)["text"]
|
||||
except NotFoundError:
|
||||
return ""
|
||||
except AppError as exc:
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
# nothing else.
|
||||
#
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.0
|
||||
# local — a read-only Gitea access token in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the Haski org secret DREDD_CORE_TOKEN; see the workflow-level `env:` in .github/workflows/
|
||||
dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.23.0
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
|
||||
@@ -115,8 +115,8 @@ check("USER app" in dockerfile, "container runs as root",
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
if "dredd-core @ git+" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
|
||||
@@ -91,12 +91,14 @@ def test_the_admin_boundary(admin_client, make_user):
|
||||
bob = make_user("bob")
|
||||
h = bearer(bob["token"])
|
||||
for method, path in [("GET", "/api/v1/admin/audit"), ("GET", "/api/v1/admin/settings"),
|
||||
("PUT", "/api/v1/admin/settings")]:
|
||||
("PUT", "/api/v1/admin/settings"), ("GET", "/api/v1/users")]:
|
||||
r = admin_client.request(method, path, headers=h, json={"values": {"instance_name": "x"}})
|
||||
assert r.status_code == 403, (path, r.status_code)
|
||||
r = admin_client.post("/api/v1/users", headers=h, json={
|
||||
"email": f"sneaky-{RUN}@example.com", "full_name": "S", "password": USER_PASSWORD})
|
||||
assert r.status_code == 403
|
||||
# The roster is administration: on the platform it is every account, not this module's users.
|
||||
assert admin_client.get("/api/v1/users").status_code == 200
|
||||
|
||||
|
||||
def test_deactivation_ends_sessions_at_once(admin_client, make_user):
|
||||
|
||||
@@ -265,3 +265,47 @@ def test_without_siblings_both_paths_refuse_cleanly(monkeypatch):
|
||||
siblings.pick_clause("t", "x", 1)
|
||||
with pytest.raises(ConflictError):
|
||||
siblings.save_to_galena("t", "x", "a.md", b"", "text/markdown")
|
||||
|
||||
|
||||
# ── bounds on the checks (security review 2026-11) ────────────────────────────
|
||||
def test_parse_amount_refuses_text_longer_than_any_amount():
|
||||
assert checks.parse_amount("999 999 999 999,99 złotych") == Decimal("999999999999.99")
|
||||
assert checks.parse_amount("1" + " " * 19_998 + "1") is None # never reaches the regexes
|
||||
assert checks.parse_amount("1" * (checks.MAX_AMOUNT_TEXT + 1)) is None
|
||||
|
||||
|
||||
def test_lexicon_check_asks_each_source_once(monkeypatch):
|
||||
import uuid
|
||||
|
||||
from app.services import siblings
|
||||
|
||||
sid, gone = str(uuid.uuid4()), str(uuid.uuid4())
|
||||
fake = _Fake({
|
||||
("GET", f"/sources/{sid}/library"): (200, {"source_title": "W", "clauses": [
|
||||
{"position": 1, "text": "Jeden."}, {"position": 2, "text": "Dwa."}]}),
|
||||
("GET", f"/sources/{gone}/library"): (403, {"detail": "no"}),
|
||||
})
|
||||
monkeypatch.setattr(siblings, "lexicon", lambda: fake)
|
||||
look = siblings.lexicon_lookup("tok")
|
||||
assert look("a", {"lexicon": {"source_id": sid, "position": 1}}) == "Jeden."
|
||||
assert look("b", {"lexicon": {"source_id": sid, "position": 2}}) == "Dwa."
|
||||
assert look("c", {"lexicon": {"source_id": gone, "position": 1}}) == ""
|
||||
assert look("d", {"lexicon": {"source_id": gone, "position": 2}}) == ""
|
||||
assert [c[1] for c in fake.calls] == [f"/sources/{sid}/library", f"/sources/{gone}/library"]
|
||||
# A new check asks again: the cache lives for one check, never across people or requests.
|
||||
siblings.lexicon_lookup("tok")("a", {"lexicon": {"source_id": sid, "position": 1}})
|
||||
assert len(fake.calls) == 3
|
||||
|
||||
|
||||
def test_lexicon_client_has_a_json_sized_body_limit(monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from dredd_core.module_client import MAX_BODY
|
||||
|
||||
from app.services import siblings
|
||||
|
||||
monkeypatch.setattr(siblings, "get_settings", lambda: SimpleNamespace(
|
||||
lexicon_url="https://example.org/lexicon", galena_url="https://example.org/galena",
|
||||
module_call_timeout=15.0))
|
||||
assert siblings.lexicon().max_body == siblings.LEXICON_MAX_BODY < MAX_BODY
|
||||
assert siblings.galena().max_body == MAX_BODY
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Scribe on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
|
||||
# over a network): an override for docker-compose.yml.
|
||||
#
|
||||
# DREDD_CORE_TOKEN=github_pat_... \
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> \
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
#
|
||||
# The database lives elsewhere — the family shares ONE managed database, and Scribe has schema
|
||||
|
||||
+1
-1
@@ -57,6 +57,6 @@ secrets:
|
||||
# Used only by the build stage's one `pip install`; no running container gets it. Compose resolves
|
||||
# the variable from the shell OR the project .env (shell wins) — keep it in the shell, because every
|
||||
# service here also loads .env at runtime and would receive the token:
|
||||
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> docker compose up -d --build
|
||||
dredd_core_token:
|
||||
environment: DREDD_CORE_TOKEN
|
||||
|
||||
Reference in New Issue
Block a user