Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ea5bf7f0e | ||
|
|
ea66e3ec31 | ||
|
|
f781bd7557 | ||
|
|
8c29520f13 | ||
|
|
59ea522f00 | ||
|
|
97e927078e | ||
|
|
8abd645c72 | ||
|
|
7256faa2c1 | ||
|
|
d410eb6c04 | ||
|
|
bc3575afef | ||
|
|
ebb4071084 | ||
|
|
e1a5f8d423 | ||
|
|
e3eeb4ff67 | ||
|
|
fbd643d21e | ||
|
|
754f73b078 | ||
|
|
3628b8e5e5 | ||
|
|
3718613db2 |
@@ -91,6 +91,9 @@ SIGNING_PKCS12_PASSPHRASE=
|
||||
SIGNING_TRUST_ROOTS=
|
||||
# /Location in the signature dictionary (optional).
|
||||
SIGNING_LOCATION=
|
||||
# Who may sign, comma-separated, the first the default: local (the PKCS#12 seal above) and signudoc
|
||||
# (SignuDoc; no API in the Start edition, so: download, sign there, upload the signed PDF).
|
||||
SIGNING_PROVIDERS=local,signudoc
|
||||
|
||||
# ── One platform, one account ────────────────────────────────────────────────
|
||||
# The shared identity schema. Empty — this stack — is STANDALONE: Parafa owns its own
|
||||
@@ -176,3 +179,7 @@ FORWARDED_ALLOW_IPS=127.0.0.1
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=parafa-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# The Archive's technical account (Atrium#53): the fixed id the hub creates it under. Here it may
|
||||
# reach only the evidence routes (GET /evidence, POST /seal); everywhere else it is a 404. Keep the default.
|
||||
ARCHIVE_READER_ID=a2c41e00-0000-4000-8000-000000000053
|
||||
|
||||
+23
-24
@@ -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
|
||||
@@ -124,11 +128,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
|
||||
@@ -265,7 +264,7 @@ jobs:
|
||||
# the whole ordering.
|
||||
run: |
|
||||
for i in $(seq 1 60); do
|
||||
if curl -fsS http://localhost/healthz >/dev/null 2>&1; then
|
||||
if curl -fsS http://localhost:8121/healthz >/dev/null 2>&1; then
|
||||
echo "ready after ~$((i * 5))s"; exit 0
|
||||
fi
|
||||
sleep 5
|
||||
@@ -277,17 +276,17 @@ jobs:
|
||||
- name: Drive it through the published backend
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -fsS http://localhost/healthz
|
||||
headers=$(curl -fsSI http://localhost/)
|
||||
curl -fsS http://localhost:8121/healthz
|
||||
headers=$(curl -fsSI http://localhost:8121/)
|
||||
echo "$headers" | grep -qi "content-security-policy" || { echo "::error::no CSP on the console"; exit 1; }
|
||||
echo "$headers" | grep -qi "x-frame-options" || { echo "::error::no frame policy on the console"; exit 1; }
|
||||
curl -fsS http://localhost/ | grep -q "<title>Parafa" || { echo "::error::console did not render"; exit 1; }
|
||||
token=$(curl -fsS -X POST http://localhost/api/v1/auth/login \
|
||||
curl -fsS http://localhost:8121/ | grep -q "<title>Parafa" || { echo "::error::console did not render"; exit 1; }
|
||||
token=$(curl -fsS -X POST http://localhost:8121/api/v1/auth/login \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"email":"admin@example.com","password":"ci-admin-password-1"}' | jq -r .token)
|
||||
[ -n "$token" ] && [ "$token" != "null" ] || { echo "::error::login returned no token"; exit 1; }
|
||||
curl -fsS -H "Authorization: Bearer $token" http://localhost/api/v1/auth/me >/dev/null
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/api/v1/auth/me)
|
||||
curl -fsS -H "Authorization: Bearer $token" http://localhost:8121/api/v1/auth/me >/dev/null
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8121/api/v1/auth/me)
|
||||
[ "$code" = "401" ] || { echo "::error::expected 401 without a session, got $code"; exit 1; }
|
||||
|
||||
- name: The least-privilege roles hold inside the container
|
||||
|
||||
+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 ────────────────────────
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Signature providers: `signing_request.provider` and the status `sent`.
|
||||
|
||||
Parafa becomes a gateway to signature providers: the operator's own PAdES seal (`local`) and an
|
||||
external one (`signudoc`, a manual flow in the Start edition). A request handed to an external
|
||||
provider waits in `sent` until the signed PDF comes back.
|
||||
|
||||
* `provider` (text, NULL on a request made before providers): `ADD COLUMN IF NOT EXISTS`, so a fresh
|
||||
database, whose `0001` built it from the metadata already, is left as it is.
|
||||
* The status CHECK (`ck_signing_request_status`) is replaced by one that also allows `sent`: dropped
|
||||
`IF EXISTS` and added again, in this transaction.
|
||||
|
||||
No new table: the columns keep `signing_request`'s grants. Downgrade refuses while a request is
|
||||
`sent` (it would break the old CHECK), then puts the old CHECK back and drops the column.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0006"
|
||||
down_revision = "0005"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
CHECK = "ck_signing_request_status"
|
||||
NEW = ("draft", "sent", "signed", "failed")
|
||||
OLD = ("draft", "signed", "failed")
|
||||
|
||||
|
||||
def _check(values: tuple[str, ...]) -> str:
|
||||
listed = ", ".join("'" + v + "'" for v in values)
|
||||
return f"ALTER TABLE signing_request ADD CONSTRAINT {CHECK} CHECK (status IN ({listed}))"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TABLE signing_request ADD COLUMN IF NOT EXISTS provider text")
|
||||
op.execute(f"ALTER TABLE signing_request DROP CONSTRAINT IF EXISTS {CHECK}")
|
||||
op.execute(_check(NEW))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
sent = op.get_bind().execute(text(
|
||||
"SELECT count(*) FROM signing_request WHERE status = 'sent'")).scalar()
|
||||
if sent:
|
||||
raise RuntimeError(f"{sent} request(s) are with an external provider (status 'sent'); "
|
||||
"withdraw them before downgrading.")
|
||||
op.execute(f"ALTER TABLE signing_request DROP CONSTRAINT IF EXISTS {CHECK}")
|
||||
op.execute(_check(OLD))
|
||||
op.execute("ALTER TABLE signing_request DROP COLUMN IF EXISTS provider")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""A signing request (the contract's party) may name its counterparty from the platform's register (spec 2026-11-25 part A).
|
||||
|
||||
One nullable column, `signing_request.counterparty_id`, a foreign key on `counterparty` ON DELETE RESTRICT
|
||||
(a counterparty is archived, never deleted). This module only READS the register: it never writes a
|
||||
counterparty, and never reads or shows `counterparty_contact`.
|
||||
|
||||
* **Standalone** (`IDENTITY_SCHEMA` empty): the register's three tables live in this schema
|
||||
(`dredd_core.counterparties.create_counterparty_tables`; a fresh database already has them, `0001`
|
||||
builds from the metadata). Nothing here writes them, so standalone they stay empty unless a
|
||||
restore brings rows: the pointer is a platform feature that keeps one code path.
|
||||
`counterparty` joins NO_DELETE.
|
||||
* **On the platform**: the register is the hub's, in the identity schema (Atrium's `0012`; its env
|
||||
lists this module's runtime role as a reader and its migrator for REFERENCES). Local copies that a
|
||||
fresh `0001` built are dropped while empty (the revision refuses when they hold rows), after the
|
||||
foreign key that pointed at them; the key is then added on the unqualified `counterparty`, which
|
||||
the search_path resolves to the hub's.
|
||||
|
||||
Idempotent: catalog checks, `IF [NOT] EXISTS`. Ends with the runtime grants.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES
|
||||
|
||||
revision = "0007"
|
||||
down_revision = "0006"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
TABLE = "signing_request"
|
||||
FK_NAME = "fk_signing_request_counterparty_id_counterparty"
|
||||
INDEX_NAME = "ix_signing_request_counterparty_id"
|
||||
_LOCAL_DROP_ORDER = ("counterparty_contact", "counterparty_alias", "counterparty")
|
||||
|
||||
|
||||
class Refused(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _q(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _has_table(bind, schema: str, table: str) -> bool:
|
||||
return bool(bind.execute(text(
|
||||
"SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
"WHERE n.nspname = :s AND c.relname = :t AND c.relkind IN ('r', 'p')"),
|
||||
{"s": schema, "t": table}).scalar())
|
||||
|
||||
|
||||
def _grants(no_delete: tuple[str, ...]) -> None:
|
||||
op.execute(runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
|
||||
no_delete=no_delete))
|
||||
|
||||
|
||||
def _link_column() -> None:
|
||||
op.execute(f"ALTER TABLE {TABLE} ADD COLUMN IF NOT EXISTS counterparty_id uuid")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
op.execute(f"ALTER TABLE {TABLE} ADD CONSTRAINT {FK_NAME} FOREIGN KEY (counterparty_id) "
|
||||
"REFERENCES counterparty (id) ON DELETE RESTRICT")
|
||||
op.execute(f"CREATE INDEX IF NOT EXISTS {INDEX_NAME} ON {TABLE} (counterparty_id)")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
if settings.shares_identity:
|
||||
identity = settings.identity_schema
|
||||
for table in sorted(COUNTERPARTY_TABLES):
|
||||
if not _has_table(bind, identity, table):
|
||||
raise Refused(f"{identity}.{table} does not exist: Atrium's revision 0012 creates "
|
||||
"the counterparty register. Migrate the hub first.")
|
||||
if _has_table(bind, own, "counterparty"):
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if _has_table(bind, own, table) and bind.execute(
|
||||
text(f"SELECT EXISTS (SELECT 1 FROM {_q(own)}.{_q(table)})")).scalar():
|
||||
raise Refused(f"{own}.{table} holds rows, and on the platform the "
|
||||
"counterparty register is the hub's. Export them if they "
|
||||
"matter, empty the table, and run the upgrade again.")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
op.execute(f"DROP TABLE IF EXISTS {_q(own)}.{_q(table)}")
|
||||
_link_column()
|
||||
_grants(NO_DELETE_TABLES)
|
||||
return
|
||||
cp.create_counterparty_tables(bind, own)
|
||||
_link_column()
|
||||
_grants((*NO_DELETE_TABLES, "counterparty"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Drops the pointer. Standalone also the (read-only, so normally empty) register, only empty."""
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
op.execute(f"DROP INDEX IF EXISTS {INDEX_NAME}")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP COLUMN IF EXISTS counterparty_id")
|
||||
if not settings.shares_identity:
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if _has_table(bind, own, table):
|
||||
if bind.execute(text(f"SELECT EXISTS (SELECT 1 FROM {_q(table)})")).scalar():
|
||||
raise Refused(f"{table} holds rows: refusing to drop the counterparty register.")
|
||||
op.execute(f"DROP TABLE {_q(table)}")
|
||||
_grants(NO_DELETE_TABLES)
|
||||
@@ -12,6 +12,7 @@ no-op instead of a crash.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
@@ -128,6 +129,11 @@ class Settings(BaseSettings):
|
||||
signing_trust_roots: str = ""
|
||||
# What the signature dictionary says (/Location); the reason is the request's own.
|
||||
signing_location: str = ""
|
||||
# Who may sign (`services/providers`), comma-separated, the first being the default: `local`
|
||||
# (the operator's PAdES seal above) and `signudoc` (SignuDoc, an external provider; in the Start
|
||||
# edition it has no API, so its flow is manual: download, sign in SignuDoc, upload the signed PDF,
|
||||
# which Parafa verifies before completing).
|
||||
signing_providers: str = "local,signudoc"
|
||||
|
||||
# ── One platform, one account ────────────────────────────────────────────────
|
||||
# The shared identity schema. Empty — the default, and what this repo's own compose stack runs —
|
||||
@@ -160,6 +166,10 @@ class Settings(BaseSettings):
|
||||
# underscores no. A two-word app therefore has a schema `my_app` and a module slug `my-app`, and
|
||||
# the scaffolder derives the second from the first so the default is already legal.
|
||||
module_slug: str = "parafa"
|
||||
# The Archive's technical account (Atrium#53): the hub creates it under this fixed id, with no
|
||||
# password, and Galena carries its read-only token. Here it reaches `GET /evidence` and
|
||||
# `POST /seal` and nothing else (deps.get_current_user). An id: nobody can register into it.
|
||||
archive_reader_id: uuid.UUID = uuid.UUID("a2c41e00-0000-4000-8000-000000000053")
|
||||
# Where people sign in when identity is shared — the hub's address as a BROWSER sees it, e.g.
|
||||
# /atrium/ on the platform. Empty standalone (there is no hub), and empty is survivable on the
|
||||
# platform too: the console then says where accounts live without linking to them. It is
|
||||
|
||||
+8
-1
@@ -29,6 +29,7 @@ from .enums import TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import authz as authz_service
|
||||
from .services import moderation as moderation_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
@@ -126,12 +127,18 @@ def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser
|
||||
if resolved is None:
|
||||
raise AuthenticationError("Your session has expired — please sign in again.")
|
||||
user, credential = resolved
|
||||
route_path = getattr(request.scope.get("route"), "path", request.url.path)
|
||||
# The Archive's technical account (Atrium#53) holds a platform credential, so without this it
|
||||
# would reach every screen here. It reaches /evidence and /seal and is refused (404) elsewhere;
|
||||
# /seal is refused (404) to everybody else. Before the scope check, so a refusal is always 404.
|
||||
authz_service.assert_archive_reader_route(user, route_path)
|
||||
|
||||
# Scope is enforced HERE and nowhere else. Every authenticated route depends on this
|
||||
# function, so one check covers all of them and no future route can forget it. Scope narrows
|
||||
# what a credential may do; it never widens it — the caller's own roles are still checked by
|
||||
# services/authz.py afterwards.
|
||||
if credential.scope == TokenScope.read.value and request.method.upper() not in SAFE_METHODS:
|
||||
if (credential.scope == TokenScope.read.value and request.method.upper() not in SAFE_METHODS
|
||||
and not authz_service.is_seal_call(user, route_path)):
|
||||
raise AuthorizationError("This app token is read-only. Create a read/write token instead.")
|
||||
|
||||
# And, for exactly the same reason, the other question every authenticated route has to ask:
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@ from .errors import ProblemDetailErrorMiddleware, install_error_handlers
|
||||
from .logging_config import configure_logging
|
||||
from .models import SHARED_TABLES
|
||||
from .observability import setup_observability
|
||||
from .routers import admin, auth, dashboard, health, signing, users
|
||||
from .routers import admin, auth, dashboard, evidence, health, signing, users
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -118,7 +118,7 @@ if settings.cors_origins_list:
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router,
|
||||
signing.router, dashboard.router,
|
||||
signing.router, dashboard.router, evidence.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@@ -39,7 +39,10 @@ from dredd_core import (
|
||||
pg_enum,
|
||||
)
|
||||
from dredd_core.events import EventCursor, EventReceipt, ModuleEvent
|
||||
from dredd_core.identity import EVENT_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, EVENT_TABLES, SHARED_IDENTITY_TABLES
|
||||
# The platform's counterparty register (dredd-core 0.21.0; spec 2026-11-25 part A), READ only:
|
||||
# standalone this schema's own tables, on the platform the hub's in the identity schema.
|
||||
from dredd_core.counterparties import Counterparty, CounterpartyAlias, CounterpartyContact
|
||||
|
||||
from .signing import SigningRequest
|
||||
|
||||
@@ -47,7 +50,7 @@ from .signing import SigningRequest
|
||||
#: identity tables and the event log. They may not exist in this app's schema there
|
||||
#: (`assert_identity_schema` in the lifespan is given this set), and a backup sweep would leave them
|
||||
#: out (`own_tables(..., shared=SHARED_TABLES)`).
|
||||
SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | EVENT_TABLES
|
||||
SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | EVENT_TABLES | COUNTERPARTY_TABLES
|
||||
|
||||
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
|
||||
# The runtime-grants migration (alembic/versions/0002_runtime_grants.py, and every later revision
|
||||
@@ -71,5 +74,6 @@ __all__ = [
|
||||
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"SigningRequest", "ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
|
||||
"Counterparty", "CounterpartyAlias", "CounterpartyContact",
|
||||
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
|
||||
]
|
||||
|
||||
@@ -5,7 +5,8 @@ work package M6).
|
||||
`dredd_core.document_ref` shapes, with no foreign key across modules (D9: a DocumentRef works only
|
||||
while Galena is enabled, `plain_files` always). The subject is always a PDF.
|
||||
|
||||
Its life is `draft -> signed | failed`, and `failed -> signed` on a retry. The **signed result** is a
|
||||
Its life is `draft -> signed | failed`, and `failed -> signed` on a retry; with an external provider
|
||||
`draft -> sent -> signed` (`sent -> draft` withdraws it). The **signed result** is a
|
||||
second reference held in the `signed_*` columns: always a new `plain_files` file (the signed bytes
|
||||
Parafa itself produced and keeps), and, when the subject is a Galena document, also the commit
|
||||
Galena answered when the signed PDF was written back to it as a new version (`signed_commit_sha`).
|
||||
@@ -33,8 +34,9 @@ from sqlalchemy import (
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
#: draft = "Do podpisu"; signed = "Podpisane"; failed = the last attempt did not sign (retry allowed).
|
||||
STATUSES = ("draft", "signed", "failed")
|
||||
#: draft = "Do podpisu"; sent = handed to an external provider (SignuDoc), the signed PDF not back
|
||||
#: yet; signed = "Podpisane"; failed = the last attempt did not sign (retry allowed).
|
||||
STATUSES = ("draft", "sent", "signed", "failed")
|
||||
|
||||
|
||||
def _one_of(column: str, values: tuple[str, ...]) -> str:
|
||||
@@ -44,6 +46,11 @@ def _one_of(column: str, values: tuple[str, ...]) -> str:
|
||||
class SigningRequest(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
|
||||
__tablename__ = "signing_request"
|
||||
|
||||
#: The counterparty from the platform's register (spec 2026-11-25 part A), READ only here:
|
||||
#: `services/counterparty_ref.py`. RESTRICT: a counterparty is archived, never deleted.
|
||||
counterparty_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("counterparty.id", ondelete="RESTRICT"), index=True)
|
||||
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
note: Mapped[str | None] = mapped_column(Text)
|
||||
#: Goes into the signature dictionary's /Reason.
|
||||
@@ -64,6 +71,9 @@ class SigningRequest(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
|
||||
signer_subject: Mapped[str | None] = mapped_column(Text)
|
||||
#: Why the last attempt failed (status = failed), in words a person can act on.
|
||||
error: Mapped[str | None] = mapped_column(Text)
|
||||
#: Who signs (`services/providers`): `local` (the operator's PAdES seal) or an external one
|
||||
#: (`signudoc`). NULL on a request made before providers, which the local seal signed.
|
||||
provider: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
__table_args__ = (
|
||||
*SubjectRefMixin.subject_ref_constraints(),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The Archive's contract (Atrium#53): evidence Galena copies into a package, and the manifest seal.
|
||||
|
||||
Downloads are paths under /api/v1/, same auth, always attachments. The Archive's technical account
|
||||
may reach these routes and nothing else here (`deps.get_current_user`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from dredd_core.plain_files import response_headers
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, extract_token, get_current_user
|
||||
from ..errors import ValidationError
|
||||
from ..models import AppUser
|
||||
from ..services import authz, evidence
|
||||
|
||||
router = APIRouter(tags=["evidence"])
|
||||
|
||||
|
||||
def _attachment(db: Session, data: bytes, name: str) -> Response:
|
||||
db.commit() # the audit row of a technical-account read
|
||||
media, headers = response_headers(name, download=True)
|
||||
return Response(data, media_type=media, headers=headers)
|
||||
|
||||
|
||||
@router.get("/evidence")
|
||||
def list_evidence(document_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = evidence.for_document(db, user, document_id, token=extract_token(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/evidence/requests/{request_id}/signed")
|
||||
def signed(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
return _attachment(db, *evidence.signed_pdf(db, user, request_id, token=extract_token(request)))
|
||||
|
||||
|
||||
@router.get("/evidence/requests/{request_id}/report")
|
||||
def report(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
return _attachment(db, *evidence.report(db, user, request_id, token=extract_token(request)))
|
||||
|
||||
|
||||
@router.post("/seal")
|
||||
async def seal(request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
"""Raw bytes in (≤ 1 MB), a detached CMS / CAdES signature by the operator's seal out."""
|
||||
authz.assert_seal_caller(user) # 404 before a single byte is read
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data += chunk
|
||||
if len(data) > evidence.SEAL_MAX_BYTES:
|
||||
raise ValidationError("Plik do opieczętowania jest za duży.", {"code": "file_too_large"})
|
||||
# `seal` runs pyHanko's coroutine with asyncio.run, which refuses inside this route's running
|
||||
# event loop (Parafa#9): run it on the thread pool, like every sync route.
|
||||
out = await run_in_threadpool(evidence.seal, db, user, bytes(data), ip=client_ip(request))
|
||||
db.commit()
|
||||
return Response(out, media_type="application/pkcs7-signature",
|
||||
headers={"Content-Disposition": 'attachment; filename="manifest.json.p7s"'})
|
||||
@@ -18,7 +18,9 @@ from ..db import get_db
|
||||
from ..deps import client_ip, extract_token, get_current_user
|
||||
from ..errors import ValidationError
|
||||
from ..models import AppUser
|
||||
from ..schemas import RequestDocumentIn
|
||||
from ..schemas import RequestCounterpartyIn, RequestDocumentIn, SendIn
|
||||
from ..services import counterparty_ref
|
||||
from ..services import providers as providers_service
|
||||
from ..services import signing as service
|
||||
|
||||
router = APIRouter(tags=["signing"])
|
||||
@@ -113,3 +115,64 @@ async def verify_upload(request: Request, file: UploadFile = File(...),
|
||||
name=file.filename or "plik.pdf", ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
# ── signature providers ─────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/providers")
|
||||
def list_providers(user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Who may sign here: the local seal and/or an external provider (SignuDoc), the first the
|
||||
default."""
|
||||
return providers_service.as_list()
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/send")
|
||||
def send(request_id: uuid.UUID, body: SendIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""Hand the request to a manual provider (`sent`): sign it there, then upload the result."""
|
||||
out = service.send(db, actor=user, request_id=request_id, provider=body.provider,
|
||||
token=extract_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/counterparties")
|
||||
def search_counterparties(q: str | None = Query(None, max_length=200),
|
||||
limit: int = Query(20, ge=1, le=counterparty_ref.MAX_SEARCH),
|
||||
db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""The request's picker: organisations of the platform's register (read only)."""
|
||||
return counterparty_ref.search(db, q, limit)
|
||||
|
||||
|
||||
@router.put("/requests/{request_id}/counterparty")
|
||||
def set_counterparty(request_id: uuid.UUID, body: RequestCounterpartyIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.set_counterparty(db, actor=user, request_id=request_id,
|
||||
counterparty_id=body.counterparty_id,
|
||||
token=extract_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/withdraw")
|
||||
def withdraw(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.withdraw(db, actor=user, request_id=request_id, token=extract_token(request),
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/signed-upload")
|
||||
async def signed_upload(request_id: uuid.UUID, request: Request, file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""The PDF signed at the provider: verified against this request's original, then completed.
|
||||
pyHanko's validation runs its own event loop, so the work goes to the thread pool."""
|
||||
data = await _read_upload(file)
|
||||
return await run_in_threadpool(
|
||||
service.complete_manual, db, actor=user, request_id=request_id, data=data,
|
||||
name=file.filename or "podpisany.pdf", token=extract_token(request), ip=client_ip(request))
|
||||
|
||||
@@ -104,6 +104,13 @@ class GrantIn(BaseModel):
|
||||
|
||||
|
||||
# ── signing requests ──────────────────────────────────────────────────────────
|
||||
class RequestCounterpartyIn(BaseModel):
|
||||
"""The contract's party from the register; `null` clears it (a PUT replaces the one value)."""
|
||||
model_config = {"extra": "forbid"}
|
||||
|
||||
counterparty_id: uuid.UUID | None
|
||||
|
||||
|
||||
class RequestDocumentIn(BaseModel):
|
||||
"""A request on a Galena document: the project id, the file's path, the version to pin."""
|
||||
document_id: uuid.UUID
|
||||
@@ -114,6 +121,11 @@ class RequestDocumentIn(BaseModel):
|
||||
reason: str | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class SendIn(BaseModel):
|
||||
"""Hand a request to a manual signature provider (`services/providers`)."""
|
||||
provider: str = Field(min_length=1, max_length=40, pattern=r"^[a-z][a-z0-9_]*$")
|
||||
|
||||
|
||||
# ── administration ────────────────────────────────────────────────────────────
|
||||
class SettingsIn(BaseModel):
|
||||
"""A partial set of settings to change, validated against `services/settings.SPECS`."""
|
||||
|
||||
@@ -29,6 +29,7 @@ from __future__ import annotations
|
||||
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import NotFoundError
|
||||
from ..models import AppUser
|
||||
from . import moderation
|
||||
@@ -63,3 +64,37 @@ def assert_moderator(db: DbSession, user: AppUser) -> AppUser:
|
||||
moderator out of the job they were given. `deps.require_moderator` is the HTTP edge of this one.
|
||||
"""
|
||||
return moderation.assert_moderator(db, user)
|
||||
|
||||
|
||||
# ── the Archive's technical account (Atrium#53) ───────────────────────────────
|
||||
#: The only routes it may reach: the evidence a Galena archive package is collected from, and the
|
||||
#: operator's seal over that package's manifest.
|
||||
EVIDENCE_PREFIX = "/api/v1/evidence"
|
||||
SEAL_ROUTE = "/api/v1/seal"
|
||||
|
||||
|
||||
def is_archive_reader(user: AppUser) -> bool:
|
||||
"""The hub's passwordless account Galena collects evidence with (fixed id, read-only token)."""
|
||||
return user.id == get_settings().archive_reader_id
|
||||
|
||||
|
||||
def is_seal_call(user: AppUser, route_path: str) -> bool:
|
||||
"""`POST /seal` by the technical account: the one write its read-only token may make (it stores
|
||||
nothing but an audit row)."""
|
||||
return route_path == SEAL_ROUTE and is_archive_reader(user)
|
||||
|
||||
|
||||
def assert_archive_reader_route(user: AppUser, route_path: str) -> None:
|
||||
"""The technical account reads evidence and seals, nothing else: 404 elsewhere, as a stranger.
|
||||
And the seal is its alone: anybody else asking for it gets 404, whatever their token's scope."""
|
||||
if route_path == SEAL_ROUTE and not is_archive_reader(user):
|
||||
raise NotFoundError("Not found.")
|
||||
if is_archive_reader(user) and not (route_path.startswith(EVIDENCE_PREFIX)
|
||||
or route_path == SEAL_ROUTE):
|
||||
raise NotFoundError("Not found.")
|
||||
|
||||
|
||||
def assert_seal_caller(user: AppUser) -> None:
|
||||
"""The seal is the Archive's alone: everybody else gets 404."""
|
||||
if not is_archive_reader(user):
|
||||
raise NotFoundError("Not found.")
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""The platform's counterparty register, READ by this module (spec 2026-11-25 part A).
|
||||
|
||||
Sygna and Galena write the register; this module only points at one of its organisations
|
||||
(`counterparty_id` on a signing request (the contract's party)) and shows its name. It never writes a counterparty and never reads
|
||||
`counterparty_contact`: the other side's people are not this module's to show. Standalone the
|
||||
register is this schema's own (empty unless restored); on the platform the hub's, through the
|
||||
search_path. The pure checks are here; the domain write that uses them is the caller's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import ValidationError
|
||||
from ..models import Counterparty
|
||||
|
||||
KIND = "organisation"
|
||||
MAX_SEARCH = 50
|
||||
|
||||
|
||||
def summary(row: Counterparty | None) -> dict[str, Any] | None:
|
||||
"""What a screen shows of a counterparty: never its contacts, address or notes."""
|
||||
if row is None:
|
||||
return None
|
||||
return {"id": str(row.id), "name": row.name, "nip": row.nip, "archived": row.archived}
|
||||
|
||||
|
||||
def of(db: DbSession, counterparty_id: uuid.UUID | None) -> dict[str, Any] | None:
|
||||
return summary(db.get(Counterparty, counterparty_id)) if counterparty_id else None
|
||||
|
||||
|
||||
def search(db: DbSession, q: str | None, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""Organisations by folded name (`search_key`) or the leading digits of a NIP / KRS; archived
|
||||
ones never offered; an empty phrase finds nothing."""
|
||||
if not 1 <= limit <= MAX_SEARCH:
|
||||
raise ValidationError(f"limit is 1..{MAX_SEARCH}.")
|
||||
key = cp.normalize(q or "")
|
||||
digits = re.sub(r"[\s-]", "", q or "")
|
||||
conditions = []
|
||||
if key:
|
||||
conditions.append(Counterparty.search_key.contains(key, autoescape=True))
|
||||
if digits.isdigit():
|
||||
conditions += [Counterparty.nip.startswith(digits, autoescape=True),
|
||||
Counterparty.krs.startswith(digits, autoescape=True)]
|
||||
if not conditions:
|
||||
return []
|
||||
rows = db.scalars(select(Counterparty)
|
||||
.where(Counterparty.kind == KIND, Counterparty.archived.is_(False),
|
||||
or_(*conditions))
|
||||
.order_by(Counterparty.name, Counterparty.id).limit(limit)).all()
|
||||
return [summary(r) for r in rows]
|
||||
|
||||
|
||||
def checked(db: DbSession, counterparty_id: uuid.UUID | None,
|
||||
current: uuid.UUID | None) -> uuid.UUID | None:
|
||||
"""`counterparty_id` when it may be pointed at: an organisation of the register, not archived
|
||||
unless it is already the `current` one. `None` (clear it) always may. Else a 422."""
|
||||
if counterparty_id is None:
|
||||
return None
|
||||
row = db.get(Counterparty, counterparty_id)
|
||||
if row is None or row.kind != KIND:
|
||||
raise ValidationError("Nie ma takiego kontrahenta.", {"code": "counterparty_unknown",
|
||||
"en": "No such counterparty."})
|
||||
if row.archived and counterparty_id != current:
|
||||
raise ValidationError("Ten kontrahent jest zarchiwizowany.",
|
||||
{"code": "counterparty_archived",
|
||||
"en": "That counterparty is archived."})
|
||||
return counterparty_id
|
||||
@@ -0,0 +1,157 @@
|
||||
"""What Galena's Archive collects from this module (Atrium#53): evidence and the manifest seal.
|
||||
|
||||
`GET /evidence?document_id=` lists, for every signed request on that Galena document, the signed PDF
|
||||
and its signature-verification report (canonical JSON). The report is computed when it is asked
|
||||
for, so it reflects the trust roots and certificate validity of that moment: the listed hash and a
|
||||
later download can differ (Parafa#9, point 4; storing the report once is the follow-up). A person sees the requests they may read (`signing.for_reading`'s rule); the
|
||||
Archive's technical account sees all of them, and each of its uses is audited (`evidence.read`).
|
||||
|
||||
`POST /seal` signs a small file (the package's manifest) with the operator's local seal as a
|
||||
detached CMS / CAdES signature. Only the technical account may call it; everybody else gets 404.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from dredd_core.plain_files import MAX_FILE_BYTES
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import AppError, NotFoundError, ValidationError
|
||||
from ..models import AppUser
|
||||
from ..models.signing import SigningRequest
|
||||
from . import audit, authz, pades, signing
|
||||
|
||||
SEAL_MAX_BYTES = 1024 * 1024
|
||||
|
||||
|
||||
def _audit(db: DbSession, user: AppUser, entity_type: str, entity_id: Any, detail: str) -> None:
|
||||
if authz.is_archive_reader(user):
|
||||
audit.record(db, actor_id=user.id, action="evidence.read", entity_type=entity_type,
|
||||
entity_id=entity_id, detail=detail)
|
||||
|
||||
|
||||
def _signed(db: DbSession, document_id: uuid.UUID) -> list[SigningRequest]:
|
||||
return list(db.scalars(
|
||||
select(SigningRequest)
|
||||
.where(SigningRequest.ref_document_id == document_id, SigningRequest.status == "signed")
|
||||
.order_by(SigningRequest.signed_at, SigningRequest.id)))
|
||||
|
||||
|
||||
def _readable(db: DbSession, user: AppUser, rows: list[SigningRequest], *,
|
||||
token: str | None) -> list[SigningRequest]:
|
||||
if authz.is_archive_reader(user):
|
||||
return rows
|
||||
mine = [r for r in rows if authz.can_read(db, user, r.owner_id)]
|
||||
return signing._readable_rows(mine, token=token)
|
||||
|
||||
|
||||
def _row(db: DbSession, user: AppUser, request_id: uuid.UUID, *, token: str | None) -> SigningRequest:
|
||||
row = db.get(SigningRequest, request_id)
|
||||
if (row is None or row.ref_document_id is None or signing.signed_ref(row) is None
|
||||
or not _readable(db, user, [row], token=token)):
|
||||
raise NotFoundError("Not found.")
|
||||
return row
|
||||
|
||||
|
||||
def report_doc(row: SigningRequest, report: dict) -> bytes:
|
||||
"""The verification report as the archive keeps it: canonical JSON."""
|
||||
doc = {"request_id": str(row.id), "document_id": str(row.ref_document_id),
|
||||
"name": row.signed_name, "sha256": row.signed_sha256, **report}
|
||||
return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
|
||||
default=str).encode("utf-8")
|
||||
|
||||
|
||||
#: How long the Archive waits for one of the two verification slots before a row gives up.
|
||||
VERIFY_WAIT_SECONDS = 30
|
||||
|
||||
|
||||
def _report(row: SigningRequest) -> bytes:
|
||||
"""A stored signed file is verified up to the size Parafa stores (not the upload limit), and
|
||||
waits for a verification slot instead of refusing at once: the Archive cannot click again."""
|
||||
ref = signing.signed_ref(row)
|
||||
return report_doc(row, signing._verify_bounded(signing.files().read(ref),
|
||||
max_bytes=MAX_FILE_BYTES,
|
||||
wait=VERIFY_WAIT_SECONDS))
|
||||
|
||||
|
||||
def items_for(row: SigningRequest, report: bytes | None) -> list[dict[str, Any]]:
|
||||
base = f"evidence/requests/{row.id}"
|
||||
signed = {"kind": "signed_pdf", "name": row.signed_name, "sha256": row.signed_sha256,
|
||||
"source_id": str(row.id), "commit_sha": row.signed_commit_sha,
|
||||
"download": f"{base}/signed"}
|
||||
if report is None:
|
||||
return [signed]
|
||||
return [
|
||||
signed,
|
||||
{"kind": "verification_report", "name": f"weryfikacja-{row.id}.json",
|
||||
"sha256": hashlib.sha256(report).hexdigest(), "source_id": str(row.id),
|
||||
"commit_sha": row.signed_commit_sha, "download": f"{base}/report"},
|
||||
]
|
||||
|
||||
|
||||
def for_document(db: DbSession, user: AppUser, document_id: uuid.UUID, *,
|
||||
token: str | None) -> dict[str, Any]:
|
||||
"""The contract's answer: always 200, empty items and a note when nothing is there. A row whose
|
||||
report cannot be made (too big, no free slot in time) still lists its signed PDF; the report is
|
||||
left out and the reason goes into the note, which the Archive keeps (Parafa#9)."""
|
||||
items: list[dict[str, Any]] = []
|
||||
problems: list[str] = []
|
||||
for row in _readable(db, user, _signed(db, document_id), token=token):
|
||||
try:
|
||||
report = _report(row)
|
||||
except AppError as exc:
|
||||
problems.append(f"Wniosek {row.id}: brak raportu weryfikacji ({exc})")
|
||||
report = None
|
||||
items += items_for(row, report)
|
||||
_audit(db, user, "document", document_id, f"{len(items)} items")
|
||||
note = "; ".join(problems) or (
|
||||
None if items else "Brak podpisanych wniosków dla tego dokumentu.")
|
||||
return {"module": get_settings().module_slug, "document_id": str(document_id),
|
||||
"items": items, "note": note}
|
||||
|
||||
|
||||
def signed_pdf(db: DbSession, user: AppUser, request_id: uuid.UUID, *,
|
||||
token: str | None) -> tuple[bytes, str]:
|
||||
row = _row(db, user, request_id, token=token)
|
||||
ref = signing.signed_ref(row)
|
||||
_audit(db, user, "signing_request", row.id, "signed_pdf")
|
||||
return signing.files().read(ref), ref.name
|
||||
|
||||
|
||||
def report(db: DbSession, user: AppUser, request_id: uuid.UUID, *,
|
||||
token: str | None) -> tuple[bytes, str]:
|
||||
row = _row(db, user, request_id, token=token)
|
||||
_audit(db, user, "signing_request", row.id, "verification_report")
|
||||
return _report(row), f"weryfikacja-{row.id}.json"
|
||||
|
||||
|
||||
# ── the manifest seal ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def cms_sign(data: bytes, signer_obj) -> bytes:
|
||||
"""A detached CAdES signature (DER) over `data` by `signer_obj`."""
|
||||
signed = asyncio.run(signer_obj.async_sign_general_data(
|
||||
data, "sha256", detached=True, use_cades=True))
|
||||
return signed.dump()
|
||||
|
||||
|
||||
def seal(db: DbSession, user: AppUser, data: bytes, *, ip: str | None = None) -> bytes:
|
||||
authz.assert_seal_caller(user)
|
||||
if not data:
|
||||
raise ValidationError("Nie ma czego opieczętować.", {"code": "seal_empty"})
|
||||
if len(data) > SEAL_MAX_BYTES:
|
||||
raise ValidationError("Plik do opieczętowania jest za duży.", {"code": "file_too_large"})
|
||||
out = cms_sign(data, pades.signer())
|
||||
audit.record(db, actor_id=user.id, action="seal.issued", entity_type="seal", entity_id=None,
|
||||
detail=f"sha256 {hashlib.sha256(data).hexdigest()}", ip=ip)
|
||||
return out
|
||||
|
||||
|
||||
__all__ = ["SEAL_MAX_BYTES", "cms_sign", "for_document", "items_for", "report", "report_doc",
|
||||
"seal", "signed_pdf"]
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Signature providers: Parafa as a gateway .
|
||||
|
||||
A provider is who puts the signature on the PDF. Two exist:
|
||||
|
||||
* **`local`** - the operator's own PAdES seal (`services/pades`, one PKCS#12). Synchronous: "Podpisz"
|
||||
signs at once. A moderator's act, as before.
|
||||
* **`signudoc`** - SignuDoc, the Start edition's default external provider. It has no API yet, so its
|
||||
flow is **manual**: the request is handed over (`sent`), the person downloads the original, signs
|
||||
it in SignuDoc and uploads the signed PDF; Parafa verifies it before completing (`signing.
|
||||
complete_manual`). An API provider later plugs in as another entry with `manual=False` and its own
|
||||
submit/collect, without changing what completing a request means.
|
||||
|
||||
Which providers are offered is `SIGNING_PROVIDERS` (comma-separated, the first the default).
|
||||
Completing is the same for every provider (`signing._complete`): the signed bytes kept as a file,
|
||||
written back to Galena for a document, audited, and `document.signed` said.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from ..config import get_settings
|
||||
from ..errors import ValidationError
|
||||
from . import pades
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Provider:
|
||||
key: str
|
||||
label: str
|
||||
#: The signature is made outside Parafa and uploaded back (no API to call).
|
||||
manual: bool
|
||||
#: Whether this installation can use it now (the seal needs its PKCS#12; a manual one needs
|
||||
#: nothing).
|
||||
configured: Callable[[], bool] = field(default=lambda: True, compare=False)
|
||||
|
||||
|
||||
LOCAL, SIGNUDOC = "local", "signudoc"
|
||||
KNOWN: dict[str, Provider] = {
|
||||
LOCAL: Provider(LOCAL, "Pieczęć operatora (PAdES)", manual=False,
|
||||
configured=lambda: pades.configured()),
|
||||
SIGNUDOC: Provider(SIGNUDOC, "SignuDoc", manual=True),
|
||||
}
|
||||
|
||||
|
||||
def enabled() -> list[Provider]:
|
||||
"""The providers this installation offers, in `SIGNING_PROVIDERS` order; unknown names are
|
||||
ignored, and an empty list falls back to `local` (what Parafa did before providers)."""
|
||||
keys = [k.strip() for k in get_settings().signing_providers.split(",") if k.strip()]
|
||||
out = [KNOWN[k] for k in dict.fromkeys(keys) if k in KNOWN]
|
||||
return out or [KNOWN[LOCAL]]
|
||||
|
||||
|
||||
def get(key: str | None) -> Provider:
|
||||
"""An enabled provider by key (None: the default), or a 422."""
|
||||
offered = enabled()
|
||||
if key is None:
|
||||
return offered[0]
|
||||
for p in offered:
|
||||
if p.key == key:
|
||||
return p
|
||||
raise ValidationError("Ten dostawca podpisu nie jest dostępny.", {"code": "provider_unknown"})
|
||||
|
||||
|
||||
def as_list() -> list[dict]:
|
||||
return [{"key": p.key, "label": p.label, "manual": p.manual, "configured": p.configured()}
|
||||
for p in enabled()]
|
||||
+250
-62
@@ -27,6 +27,7 @@ import datetime as dt
|
||||
import logging
|
||||
import threading
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
|
||||
from dredd_core import document_ref, stats_contract
|
||||
@@ -41,7 +42,7 @@ from sqlalchemy.orm import Session as DbSession
|
||||
from ..config import get_settings
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..models import AppUser, SigningRequest
|
||||
from . import audit, authz, moderation, pades
|
||||
from . import audit, authz, counterparty_ref, moderation, pades, providers
|
||||
|
||||
MAX_TITLE = 200
|
||||
MAX_NOTE = 4000
|
||||
@@ -54,8 +55,9 @@ log = logging.getLogger("parafa.signing")
|
||||
#: The event a signature writes (the plan's first events, "Praca w dredd-core").
|
||||
DOCUMENT_SIGNED = "document.signed"
|
||||
|
||||
#: The two lists, and therefore the two tiles: what is still to sign, and what is signed.
|
||||
VIEWS = {"todo": ("draft", "failed"), "signed": ("signed",)}
|
||||
#: The two lists, and therefore the two tiles: what is still to sign (with an external provider
|
||||
#: too), and what is signed.
|
||||
VIEWS = {"todo": ("draft", "sent", "failed"), "signed": ("signed",)}
|
||||
|
||||
|
||||
@lru_cache
|
||||
@@ -98,12 +100,32 @@ def signed_ref(row: SigningRequest) -> FileRef | None:
|
||||
name=row.signed_name)
|
||||
|
||||
|
||||
def as_dict(db: DbSession, row: SigningRequest, user: AppUser) -> dict:
|
||||
@dataclass(frozen=True)
|
||||
class Viewer:
|
||||
"""What every row's `can_*` flags need about the person and the installation, read once per
|
||||
request or list rather than once per row."""
|
||||
moderator: bool
|
||||
local: bool
|
||||
manual: bool
|
||||
|
||||
|
||||
def viewer(db: DbSession, user: AppUser) -> Viewer:
|
||||
offered = providers.enabled()
|
||||
return Viewer(moderator=moderation.is_moderator(db, user),
|
||||
local=any(p.key == providers.LOCAL for p in offered),
|
||||
manual=any(p.manual for p in offered))
|
||||
|
||||
|
||||
def as_dict(db: DbSession, row: SigningRequest, user: AppUser, ctx: Viewer | None = None) -> dict:
|
||||
ctx = ctx or viewer(db, user)
|
||||
ref = row.ref
|
||||
return {
|
||||
"id": str(row.id), "title": row.title, "note": row.note, "reason": row.reason,
|
||||
"status": row.status, "ref": document_ref.to_dict(ref), "name": ref_name(ref),
|
||||
"on_galena": isinstance(ref, DocumentRef),
|
||||
# The contract's party from the register, for reference and the archive only: the signers
|
||||
# are still described by their certificate's subject alone.
|
||||
"counterparty": counterparty_ref.of(db, row.counterparty_id),
|
||||
"owner_name": _name_of(db, row.owner_id), "mine": row.owner_id == user.id,
|
||||
"created_at": _iso(row.created_at), "updated_at": _iso(row.updated_at),
|
||||
"signed": None if row.signed_file_id is None else {
|
||||
@@ -112,14 +134,21 @@ def as_dict(db: DbSession, row: SigningRequest, user: AppUser) -> dict:
|
||||
"by_name": _name_of(db, row.signed_by), "signer": row.signer_subject,
|
||||
},
|
||||
"error": row.error,
|
||||
"can_sign": row.status in VIEWS["todo"] and moderation.is_moderator(db, user),
|
||||
"provider": row.provider,
|
||||
# Signing is a moderator's act whoever the provider: the local seal, or completing a manual
|
||||
# one with the signed upload. Handing over and taking back: the owner or a moderator.
|
||||
"can_sign": row.status in ("draft", "failed") and ctx.moderator and ctx.local,
|
||||
"can_send": row.status in ("draft", "failed") and ctx.manual,
|
||||
"awaiting_upload": row.status == "sent",
|
||||
"can_withdraw": row.status == "sent",
|
||||
"can_complete": row.status == "sent" and ctx.moderator,
|
||||
}
|
||||
|
||||
|
||||
# ── access ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
#: How many projects one `POST /projects/roles` asks about.
|
||||
#: How many document ids one `POST /projects/roles` call carries.
|
||||
ROLES_BATCH = 200
|
||||
|
||||
|
||||
@@ -166,8 +195,8 @@ def for_reading(db: DbSession, user: AppUser, request_id: uuid.UUID, *,
|
||||
return row
|
||||
|
||||
|
||||
def _visible(db: DbSession, user: AppUser):
|
||||
stmt = select(SigningRequest)
|
||||
def _visible(db: DbSession, user: AppUser, *columns):
|
||||
stmt = select(*columns) if columns else select(SigningRequest)
|
||||
if not moderation.is_moderator(db, user):
|
||||
stmt = stmt.where(SigningRequest.owner_id == user.id)
|
||||
return stmt
|
||||
@@ -196,32 +225,45 @@ def _literal_like(q: str) -> str:
|
||||
|
||||
def list_requests(db: DbSession, user: AppUser, *, view: str | None = None, q: str = "",
|
||||
token: str | None) -> list[dict]:
|
||||
"""A list the person may see: `todo` (Do podpisu: draft + failed), `signed` (Podpisane), or all.
|
||||
Rows on a Galena document this person may not read there are left out (`for_reading`'s rule)."""
|
||||
return [as_dict(db, r, user) for r in _rows(db, user, view=view, q=q, token=token)]
|
||||
"""A list the person may see: `todo` (Do podpisu: draft + sent + failed), `signed`
|
||||
(Podpisane), or all. Rows on a Galena document this person may not read there are left out
|
||||
(`for_reading`'s rule)."""
|
||||
ctx = viewer(db, user)
|
||||
return [as_dict(db, r, user, ctx) for r in _rows(db, user, view=view, q=q, token=token)]
|
||||
|
||||
|
||||
def count(db: DbSession, user: AppUser, view: str, *, token: str | None) -> int:
|
||||
"""The length of `list_requests(view=view)` for this person: the very same rows, counted (the
|
||||
Galena filter is a call, not SQL, so the rows are read rather than COUNTed)."""
|
||||
return len(_rows(db, user, view=view, q="", token=token))
|
||||
def _tally(rows) -> dict[str, int]:
|
||||
"""How many of `rows` (already through the Galena filter) each list holds."""
|
||||
return {view: sum(1 for r in rows if r.status in statuses) for view, statuses in VIEWS.items()}
|
||||
|
||||
|
||||
def counts(db: DbSession, user: AppUser, *, token: str | None) -> dict[str, int]:
|
||||
"""The length of every `list_requests(view=...)` for this person: the same visibility and the
|
||||
same Galena filter, in one query (status + document id only) and one Galena call."""
|
||||
rows = db.execute(_visible(db, user, SigningRequest.status,
|
||||
SigningRequest.ref_document_id)).all()
|
||||
return _tally(_readable_rows(rows, token=token))
|
||||
|
||||
|
||||
def dashboard(db: DbSession, user: AppUser, *, token: str | None) -> dict:
|
||||
todo = list_requests(db, user, view="todo", token=token)
|
||||
return {"cards": {"todo": len(todo), "signed": count(db, user, "signed", token=token)},
|
||||
"recent": todo[:8], "signing_configured": pades.configured(),
|
||||
"signer": pades.signer_subject(), "galena": galena() is not None}
|
||||
"""One pass: every visible row, filtered once through Galena; the cards and the recent list are
|
||||
both read off it, so a card always equals its list."""
|
||||
rows = _rows(db, user, view=None, q="", token=token)
|
||||
ctx = viewer(db, user)
|
||||
recent = [r for r in rows if r.status in VIEWS["todo"]][:8]
|
||||
return {"cards": _tally(rows), "recent": [as_dict(db, r, user, ctx) for r in recent],
|
||||
"signing_configured": pades.configured(),
|
||||
"signer": pades.signer_subject(), "galena": galena() is not None,
|
||||
"providers": providers.as_list()}
|
||||
|
||||
|
||||
def module_stats(db: DbSession, user: AppUser, *, token: str | None = None) -> dict:
|
||||
def module_stats(db: DbSession, user: AppUser, *, token: str | None) -> dict:
|
||||
"""`GET /stats`: dredd-core's stats contract. Each tile is the length of the list its link opens
|
||||
for this person, counted with the very filter that list applies (`count` <-> `list_requests`)."""
|
||||
for this person, counted with the very filter that list applies (`counts` <-> `list_requests`)."""
|
||||
n = counts(db, user, token=token)
|
||||
tiles = [
|
||||
stats_contract.make_tile(key="to_sign", label="Do podpisu",
|
||||
count=count(db, user, "todo", token=token), link="todo"),
|
||||
stats_contract.make_tile(key="signed", label="Podpisane",
|
||||
count=count(db, user, "signed", token=token), link="signed"),
|
||||
stats_contract.make_tile(key="to_sign", label="Do podpisu", count=n["todo"], link="todo"),
|
||||
stats_contract.make_tile(key="signed", label="Podpisane", count=n["signed"], link="signed"),
|
||||
]
|
||||
return stats_contract.make_response(get_settings().module_slug, tiles)
|
||||
|
||||
@@ -349,27 +391,84 @@ def _fail(db: DbSession, row: SigningRequest, actor: AppUser, message: str, ip:
|
||||
db.commit()
|
||||
|
||||
|
||||
def sign(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, token: str | None,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Sign the request's PDF with the operator's certificate. Commits itself, as an upload does:
|
||||
the signed bytes and the row land together, the bytes first, so a signed row always has its
|
||||
file. Raises after recording `failed` when the document could not be signed."""
|
||||
moderation.assert_moderator(db, actor)
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
def _lock(db: DbSession, row: SigningRequest) -> None:
|
||||
db.scalars(select(SigningRequest).where(SigningRequest.id == row.id).with_for_update()
|
||||
.execution_options(populate_existing=True)).all()
|
||||
if row.status not in VIEWS["todo"]:
|
||||
raise ConflictError("Ten wniosek jest już podpisany.", {"code": "already_signed"})
|
||||
|
||||
|
||||
def _verify_bounded(data: bytes, *, max_bytes: int = VERIFY_MAX_BYTES, wait: float = 0) -> dict:
|
||||
"""`pades.verify` within the limits every upload shares: at most `max_bytes` (`VERIFY_MAX_BYTES`
|
||||
for an upload), and at most two validations at once across the process. A third is a 409 to
|
||||
retry, unless the caller can afford to wait up to `wait` seconds for a slot (the Archive can)."""
|
||||
if len(data) > max_bytes:
|
||||
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
|
||||
if not (_VERIFYING.acquire(timeout=wait) if wait > 0 else _VERIFYING.acquire(blocking=False)):
|
||||
raise ConflictError("Trwają inne weryfikacje; spróbuj za chwilę.", {"code": "verify_busy"})
|
||||
try:
|
||||
return pades.verify(data)
|
||||
finally:
|
||||
_VERIFYING.release()
|
||||
|
||||
|
||||
def _keep(row: SigningRequest, signed: bytes, *, token: str | None) -> tuple[FileRef, str | None]:
|
||||
"""Store the signed bytes as a new file and, for a Galena document, write them back as a new
|
||||
version. The caller deletes the file again if anything after this fails."""
|
||||
saved = files().save(signed, pades.signed_name(ref_name(row.ref)))
|
||||
commit = None
|
||||
if isinstance(row.ref, DocumentRef):
|
||||
commit = _write_back_to_galena(row.ref, signed, token=token)
|
||||
return saved, commit
|
||||
|
||||
|
||||
def _complete(db: DbSession, row: SigningRequest, actor: AppUser, *, saved: FileRef,
|
||||
commit: str | None, signer_subject: str | None, provider: str,
|
||||
ip: str | None) -> None:
|
||||
"""What finishing a request means, for every provider: the result on the row, the audit entry
|
||||
and `document.signed`, in one commit. On failure the stored file is deleted again (a Galena
|
||||
version that landed stays in Galena's history: it is the person's own write there)."""
|
||||
try:
|
||||
row.status = "signed"
|
||||
row.error = None
|
||||
row.provider = provider
|
||||
row.signed_file_id, row.signed_sha256 = saved.file_id, saved.sha256
|
||||
row.signed_size, row.signed_name = saved.size, saved.name
|
||||
row.signed_commit_sha = commit
|
||||
row.signed_by = actor.id
|
||||
row.signed_at = dt.datetime.now(dt.UTC)
|
||||
row.signer_subject = signer_subject
|
||||
db.flush()
|
||||
audit.record(db, action="signing.signed", entity_type="signing_request", entity_id=row.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{provider} {saved.sha256[:16]}"
|
||||
+ (f" galena {commit[:12]}" if commit else ""))
|
||||
core_events.emit(db, DOCUMENT_SIGNED, source_module=get_settings().module_slug,
|
||||
payload=event_payload(row))
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
files().delete(saved.file_id)
|
||||
raise
|
||||
|
||||
|
||||
def sign(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, token: str | None,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Sign the request's PDF with the operator's certificate (provider `local`). Commits itself, as
|
||||
an upload does: the signed bytes and the row land together, the bytes first, so a signed row
|
||||
always has its file. Raises after recording `failed` when the document could not be signed."""
|
||||
moderation.assert_moderator(db, actor)
|
||||
providers.get(providers.LOCAL) # 422 when this installation does not offer the seal
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
_lock(db, row)
|
||||
if row.status not in ("draft", "failed"):
|
||||
raise ConflictError("Ten wniosek jest już podpisany albo czeka u dostawcy.",
|
||||
{"code": "already_signed" if row.status == "signed" else "sent"})
|
||||
signer = pades.signer() # the operator's problem: a 409 that changes nothing
|
||||
|
||||
saved: FileRef | None = None
|
||||
try:
|
||||
data = document_ref.read(row.ref, files=files(), galena=galena(), token=token)
|
||||
signed = pades.sign(data, reason=row.reason, signer_obj=signer)
|
||||
saved = files().save(signed, pades.signed_name(ref_name(row.ref)))
|
||||
commit = None
|
||||
if isinstance(row.ref, DocumentRef):
|
||||
commit = _write_back_to_galena(row.ref, signed, token=token)
|
||||
saved, commit = _keep(row, signed, token=token)
|
||||
except Exception as exc: # noqa: BLE001 - every failure is recorded on the request, then raised
|
||||
db.rollback()
|
||||
if saved is not None:
|
||||
@@ -386,28 +485,122 @@ def sign(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, token: str | N
|
||||
if isinstance(exc, AppError):
|
||||
raise
|
||||
raise ConflictError(message[:500], {"code": "signing_failed"}) from exc
|
||||
try:
|
||||
row.status = "signed"
|
||||
row.error = None
|
||||
row.signed_file_id, row.signed_sha256 = saved.file_id, saved.sha256
|
||||
row.signed_size, row.signed_name = saved.size, saved.name
|
||||
row.signed_commit_sha = commit
|
||||
row.signed_by = actor.id
|
||||
row.signed_at = dt.datetime.now(dt.UTC)
|
||||
row.signer_subject = signer.signing_cert.subject.human_friendly
|
||||
_complete(db, row, actor, saved=saved, commit=commit, provider=providers.LOCAL,
|
||||
signer_subject=signer.signing_cert.subject.human_friendly, ip=ip)
|
||||
return as_dict(db, row, actor)
|
||||
|
||||
|
||||
# ── an external provider, by hand (SignuDoc) ─────────────────────────────────
|
||||
|
||||
|
||||
def send(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, provider: str,
|
||||
token: str | None, ip: str | None = None) -> dict:
|
||||
"""Hand the request to a manual provider: `draft|failed -> sent`. The person then downloads the
|
||||
original, signs it there and uploads the result (`complete_manual`). The owner or a moderator.
|
||||
No commit."""
|
||||
chosen = providers.get(provider)
|
||||
if not chosen.manual:
|
||||
raise ValidationError("Ten dostawca podpisuje od razu; użyj „Podpisz”.",
|
||||
{"code": "provider_not_manual"})
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
_lock(db, row)
|
||||
if row.status not in ("draft", "failed"):
|
||||
raise ConflictError("Ten wniosek nie czeka na przekazanie.", {"code": "not_draft"})
|
||||
row.status, row.provider, row.error = "sent", chosen.key, None
|
||||
db.flush()
|
||||
audit.record(db, action="signing.sent", entity_type="signing_request", entity_id=row.id,
|
||||
actor_id=actor.id, detail=chosen.key, ip=ip)
|
||||
return as_dict(db, row, actor)
|
||||
|
||||
|
||||
def set_counterparty(db: DbSession, *, actor: AppUser, request_id: uuid.UUID,
|
||||
counterparty_id: uuid.UUID | None, token: str | None,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Name the contract's party from the platform's register (`None` clears it), in any status:
|
||||
it is a reference for the archive, never a signer. Whoever may read the request and is its owner
|
||||
or a moderator; anybody else a 404. Read-only on the register. Audited when it changes. No commit."""
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
if row.owner_id != actor.id and not moderation.is_moderator(db, actor):
|
||||
raise NotFoundError("Not found.")
|
||||
before = row.counterparty_id
|
||||
row.counterparty_id = counterparty_ref.checked(db, counterparty_id, before)
|
||||
if row.counterparty_id != before:
|
||||
db.flush()
|
||||
audit.record(db, action="signing.signed", entity_type="signing_request", entity_id=row.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{saved.sha256[:16]}" + (f" galena {commit[:12]}" if commit else ""))
|
||||
core_events.emit(db, DOCUMENT_SIGNED, source_module=get_settings().module_slug,
|
||||
payload=event_payload(row))
|
||||
db.commit()
|
||||
audit.record(db, action="signing.counterparty", entity_type="signing_request",
|
||||
entity_id=row.id, actor_id=actor.id, ip=ip,
|
||||
diff={"counterparty_id": [str(before) if before else None,
|
||||
str(row.counterparty_id) if row.counterparty_id
|
||||
else None]})
|
||||
return as_dict(db, row, actor)
|
||||
|
||||
|
||||
def withdraw(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, token: str | None,
|
||||
ip: str | None = None) -> dict:
|
||||
"""Take a request back from the provider: `sent -> draft`. No commit."""
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
_lock(db, row)
|
||||
if row.status != "sent":
|
||||
raise ConflictError("Ten wniosek nie jest u dostawcy.", {"code": "not_sent"})
|
||||
audit.record(db, action="signing.withdrawn", entity_type="signing_request", entity_id=row.id,
|
||||
actor_id=actor.id, detail=row.provider, ip=ip)
|
||||
row.status, row.provider = "draft", None
|
||||
db.flush()
|
||||
return as_dict(db, row, actor)
|
||||
|
||||
|
||||
def check_signed_upload(original: bytes, signed: bytes, report: dict) -> str | None:
|
||||
"""Why an uploaded "signed" PDF is not the signed version of this request's PDF, or None.
|
||||
|
||||
* It must CONTAIN the original unchanged: a PAdES signature is an incremental update, so the
|
||||
signed file starts with the bytes that were signed. That binds the upload to this request.
|
||||
* It must carry at least one signature, and every one must be intact (the signed bytes not
|
||||
changed since).
|
||||
* The LAST signature must cover the whole file: anything appended after it (an unsigned
|
||||
incremental update) is content nobody signed, so it is refused rather than kept. Trust in the signer's certificate is reported, not required: SignuDoc's CA
|
||||
may not be among `SIGNING_TRUST_ROOTS`, and the lawyer reads the report.
|
||||
"""
|
||||
if not signed.startswith(original) or len(signed) == len(original):
|
||||
return "To nie jest podpisana wersja tego dokumentu (plik nie zawiera oryginału bez zmian)."
|
||||
if not report.get("count"):
|
||||
return "W pliku nie ma podpisu."
|
||||
if not all(s.get("intact") for s in report.get("signatures") or []):
|
||||
return "Podpis w pliku jest uszkodzony albo plik zmieniono po podpisaniu."
|
||||
if (report["signatures"][-1].get("coverage") or "") != "ENTIRE_FILE":
|
||||
return "Po ostatnim podpisie plik zmieniono (ostatni podpis nie obejmuje całego pliku)."
|
||||
return None
|
||||
|
||||
|
||||
def complete_manual(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, data: bytes,
|
||||
name: str, token: str | None, ip: str | None = None) -> dict:
|
||||
"""The signed PDF is back from a manual provider: verified, then completed like any signature.
|
||||
A moderator's act, as signing with the seal is. Commits itself. A refused upload leaves the
|
||||
request `sent`."""
|
||||
moderation.assert_moderator(db, actor)
|
||||
row = for_reading(db, actor, request_id, token=token)
|
||||
if row.status != "sent":
|
||||
raise ConflictError("Ten wniosek nie czeka na podpisany plik.", {"code": "not_sent"})
|
||||
if len(data) > VERIFY_MAX_BYTES: # before reading the original, not only before verifying
|
||||
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
|
||||
pades.check_pdf(name, data)
|
||||
original = document_ref.read(row.ref, files=files(), galena=galena(), token=token)
|
||||
report = _verify_bounded(data)
|
||||
refusal = check_signed_upload(original, data, report)
|
||||
if refusal:
|
||||
raise ValidationError(refusal, {"code": "signed_upload_refused"})
|
||||
_lock(db, row)
|
||||
if row.status != "sent": # somebody completed or withdrew it meanwhile
|
||||
raise ConflictError("Ten wniosek nie czeka na podpisany plik.", {"code": "not_sent"})
|
||||
saved: FileRef | None = None
|
||||
try:
|
||||
saved, commit = _keep(row, data, token=token)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
files().delete(saved.file_id)
|
||||
# A Galena version that landed before a failure here stays in Galena's history: it is the
|
||||
# person's own write there, and Galena's to show.
|
||||
if saved is not None:
|
||||
files().delete(saved.file_id)
|
||||
raise
|
||||
signer = next((s.get("signer") for s in reversed(report["signatures"]) if s.get("signer")), None)
|
||||
_complete(db, row, actor, saved=saved, commit=commit, provider=row.provider or "manual",
|
||||
signer_subject=signer, ip=ip)
|
||||
return as_dict(db, row, actor)
|
||||
|
||||
|
||||
@@ -421,12 +614,7 @@ def verify_upload(db: DbSession, user: AppUser, *, data: bytes, name: str,
|
||||
if len(data) > VERIFY_MAX_BYTES:
|
||||
raise ValidationError("Plik do weryfikacji jest za duży.", {"code": "file_too_large"})
|
||||
pades.check_pdf(name, data)
|
||||
if not _VERIFYING.acquire(blocking=False):
|
||||
raise ConflictError("Trwają inne weryfikacje; spróbuj za chwilę.", {"code": "verify_busy"})
|
||||
try:
|
||||
report = pades.verify(data)
|
||||
finally:
|
||||
_VERIFYING.release()
|
||||
report = _verify_bounded(data)
|
||||
audit.record(db, action="signing.verified", entity_type="signing_request", entity_id=None,
|
||||
actor_id=user.id, detail=f"{name[:200]}: {report['count']}", ip=ip)
|
||||
return {"name": name, "sha256": document_ref.sha256_of(data), **report}
|
||||
|
||||
@@ -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
|
||||
@@ -41,6 +41,8 @@ pydantic-settings==2.7.1
|
||||
SQLAlchemy==2.0.50
|
||||
alembic==1.14.0
|
||||
pg8000==1.31.2 # pure-Python PostgreSQL driver, BSD-3-Clause (no LGPL, no libpq)
|
||||
scramp==1.4.6 # pg8000's SCRAM, MIT-0. Held below 1.5.0: with pg8000 1.31.2 it breaks a
|
||||
# TLS connection (make_channel_binding; Atrium#53). Lift with a pg8000 that fixes it.
|
||||
|
||||
# Auth
|
||||
argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depends on it too, so
|
||||
|
||||
@@ -116,8 +116,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))
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Drives the console's `#/new?...` route with a stubbed DOM (run by test_new_from_link_console.py).
|
||||
// Prints one JSON line: what the route opened and what saving it would POST.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
|
||||
const src = fs.readFileSync(process.argv[2], 'utf8');
|
||||
const hash = process.argv[3];
|
||||
|
||||
// Anything the console touches that this test does not care about: callable, indexable, inert.
|
||||
const inert = new Proxy(function () {}, {
|
||||
get: (_t, k) => (k === Symbol.toPrimitive ? () => '' : inert),
|
||||
apply: () => inert,
|
||||
construct: () => inert,
|
||||
});
|
||||
const elements = {};
|
||||
const el = (id) => elements[id] || inert;
|
||||
const document = new Proxy({
|
||||
baseURI: 'http://localhost/', title: 'Parafa',
|
||||
getElementById: el,
|
||||
activeElement: null,
|
||||
}, { get: (t, k) => (k in t ? t[k] : inert) });
|
||||
const ctx = {
|
||||
document, console, URL, URLSearchParams, FormData: class {}, setTimeout, clearTimeout,
|
||||
location: { hash },
|
||||
localStorage: { getItem: () => null, setItem() {}, removeItem() {} },
|
||||
navigator: { language: 'pl' },
|
||||
};
|
||||
ctx.window = new Proxy(ctx, { get: (t, k) => (k in t ? t[k] : inert) });
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(src, ctx);
|
||||
|
||||
const out = {};
|
||||
vm.runInContext(`
|
||||
state.user = { id: 'u' };
|
||||
state.galena = true;
|
||||
viewDashboard = async () => {};
|
||||
localize = () => {};
|
||||
modal = (title, sub, body) => { __out.title = title; __out.body = body; };
|
||||
closeModal = () => {};
|
||||
toast = () => {};
|
||||
api = async (method, path, body) => { (__out.calls = __out.calls || []).push({ method, path, body }); return { id: 'r1' }; };
|
||||
`, Object.assign(ctx, { __out: out }));
|
||||
|
||||
(async () => {
|
||||
await vm.runInContext('router()', ctx);
|
||||
// Fill the stubbed form the way a person leaves it: no file, the prefilled fields untouched.
|
||||
const field = (value) => ({ value, files: [] });
|
||||
const attr = (name) => (out.body.match(new RegExp(`id="${name}"[^>]*value="([^"]*)"`)) || [])[1] || '';
|
||||
const unesc = (v) => v.replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/'/g, "'").replace(/&/g, '&');
|
||||
Object.assign(elements, {
|
||||
nqTitle: field(unesc(attr('nqTitle'))), nqReason: field(''), nqNote: field(''),
|
||||
nqFile: field(''), nqDoc: field(unesc(attr('nqDoc'))), nqPath: field(unesc(attr('nqPath'))),
|
||||
nqVersion: field(unesc(attr('nqVersion'))),
|
||||
});
|
||||
vm.runInContext('saveRequestNew()', ctx);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
})().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,82 @@
|
||||
"""The read-only counterparty pointer (spec 2026-11-25 part A), DB-free: the checks, what is shown
|
||||
(never the contacts), the model's key and revision 0007's shape."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import inspect
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.models import SHARED_TABLES, Base
|
||||
from app.services import counterparty_ref
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class _Db:
|
||||
def __init__(self, row):
|
||||
self.row = row
|
||||
|
||||
def get(self, model, key):
|
||||
return self.row if self.row is not None and self.row.id == key else None
|
||||
|
||||
|
||||
def _row(**kw):
|
||||
return SimpleNamespace(**{"id": uuid.uuid4(), "kind": "organisation", "name": "Acme",
|
||||
"nip": "5260250995", "archived": False, **kw})
|
||||
|
||||
|
||||
def test_checked_accepts_an_organisation_and_clearing():
|
||||
row = _row()
|
||||
assert counterparty_ref.checked(_Db(row), row.id, None) == row.id
|
||||
assert counterparty_ref.checked(_Db(row), None, row.id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("row,current,code", [
|
||||
(None, None, "counterparty_unknown"),
|
||||
(_row(kind="person"), None, "counterparty_unknown"),
|
||||
(_row(archived=True), None, "counterparty_archived")])
|
||||
def test_checked_refuses(row, current, code):
|
||||
with pytest.raises(ValidationError) as err:
|
||||
counterparty_ref.checked(_Db(row), row.id if row else uuid.uuid4(), current)
|
||||
assert err.value.extra["code"] == code
|
||||
|
||||
|
||||
def test_an_archived_one_already_named_stays():
|
||||
row = _row(archived=True)
|
||||
assert counterparty_ref.checked(_Db(row), row.id, row.id) == row.id
|
||||
|
||||
|
||||
def test_summary_shows_no_contact_data():
|
||||
out = counterparty_ref.summary(_row(email="x@y", phone="1", address="a", notes="n"))
|
||||
assert set(out) == {"id", "name", "nip", "archived"}
|
||||
assert counterparty_ref.summary(None) is None
|
||||
|
||||
|
||||
def test_search_of_nothing_asks_nothing():
|
||||
assert counterparty_ref.search(None, " ") == []
|
||||
with pytest.raises(ValidationError):
|
||||
counterparty_ref.search(None, "x", limit=0)
|
||||
|
||||
|
||||
def test_the_pointer_is_a_restrict_key_and_the_register_is_the_platforms():
|
||||
table = Base.metadata.tables["signing_request"]
|
||||
fk = next(fk for fk in table.foreign_keys if fk.column.table.name == "counterparty")
|
||||
assert fk.ondelete == "RESTRICT" and table.c.counterparty_id.nullable
|
||||
assert {"counterparty", "counterparty_alias", "counterparty_contact"} <= SHARED_TABLES
|
||||
|
||||
|
||||
def test_revision_0007_is_guarded_and_ends_with_the_grants():
|
||||
path = BACKEND / "alembic" / "versions" / "0007_request_counterparty.py"
|
||||
spec = importlib.util.spec_from_file_location("rev0007", path)
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0007", "0006")
|
||||
up = inspect.getsource(rev.upgrade)
|
||||
assert up.count("_grants(") == 2 and "holds rows" in up
|
||||
col = inspect.getsource(rev._link_column)
|
||||
assert "IF NOT EXISTS" in col and "ON DELETE RESTRICT" in col
|
||||
@@ -0,0 +1,193 @@
|
||||
"""DB-free tests of the Archive's contract (Atrium#53): evidence, the manifest seal and the fence
|
||||
around the technical account."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from asn1crypto import cms
|
||||
from fastapi.testclient import TestClient
|
||||
from pki import make_signer
|
||||
|
||||
from app import config, main
|
||||
from app.db import get_db
|
||||
from app.errors import NotFoundError
|
||||
from app.services import audit, authz, evidence, signing
|
||||
from app.services import auth as auth_service
|
||||
from app.services import moderation as moderation_service
|
||||
|
||||
DOC = uuid.uuid4()
|
||||
READER = config.get_settings().archive_reader_id
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def signer_env(tmp_path, monkeypatch):
|
||||
p12, passphrase, _pem = make_signer(tmp_path / "pki")
|
||||
monkeypatch.setenv("SIGNING_PKCS12_PATH", str(p12))
|
||||
monkeypatch.setenv("SIGNING_PKCS12_PASSPHRASE", passphrase)
|
||||
config.get_settings.cache_clear()
|
||||
yield
|
||||
config.get_settings.cache_clear()
|
||||
|
||||
|
||||
def _row():
|
||||
return SimpleNamespace(id=uuid.uuid4(), ref_document_id=DOC, owner_id=uuid.uuid4(),
|
||||
signed_file_id=uuid.uuid4(), signed_sha256="a" * 64, signed_size=10,
|
||||
signed_name="umowa-podpisana.pdf", signed_commit_sha="c" * 40)
|
||||
|
||||
|
||||
def test_items_and_canonical_report():
|
||||
row = _row()
|
||||
rep = evidence.report_doc(row, {"count": 1, "all_valid": True, "signatures": []})
|
||||
assert rep == evidence.report_doc(row, {"signatures": [], "all_valid": True, "count": 1})
|
||||
assert json.loads(rep)["sha256"] == "a" * 64
|
||||
pdf, report = evidence.items_for(row, rep)
|
||||
assert pdf == {"kind": "signed_pdf", "name": "umowa-podpisana.pdf", "sha256": "a" * 64,
|
||||
"source_id": str(row.id), "commit_sha": "c" * 40,
|
||||
"download": f"evidence/requests/{row.id}/signed"}
|
||||
assert report["kind"] == "verification_report"
|
||||
assert report["sha256"] == hashlib.sha256(rep).hexdigest()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def two_rows(monkeypatch):
|
||||
rows = [_row(), _row()]
|
||||
audited = []
|
||||
monkeypatch.setattr(evidence, "_signed", lambda db, d: rows)
|
||||
monkeypatch.setattr(evidence, "_report", lambda row: b"{}")
|
||||
monkeypatch.setattr(authz, "can_read", lambda db, user, owner: owner == rows[0].owner_id)
|
||||
monkeypatch.setattr(signing, "_readable_rows", lambda rs, token: rs)
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
|
||||
return rows, audited
|
||||
|
||||
|
||||
def test_person_filtered_and_unaudited(two_rows):
|
||||
rows, audited = two_rows
|
||||
out = evidence.for_document(None, SimpleNamespace(id=uuid.uuid4()), DOC, token="t")
|
||||
assert out["module"] == "parafa" and {i["source_id"] for i in out["items"]} == {str(rows[0].id)}
|
||||
assert audited == []
|
||||
|
||||
|
||||
def test_technical_account_sees_all_audited(two_rows):
|
||||
_rows, audited = two_rows
|
||||
out = evidence.for_document(None, SimpleNamespace(id=READER), DOC, token="t")
|
||||
assert len(out["items"]) == 4 and out["note"] is None
|
||||
assert audited[0]["action"] == "evidence.read" and audited[0]["entity_id"] == DOC
|
||||
|
||||
|
||||
def test_nothing_is_a_note(monkeypatch):
|
||||
monkeypatch.setattr(evidence, "_signed", lambda db, d: [])
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: None)
|
||||
out = evidence.for_document(None, SimpleNamespace(id=READER), DOC, token=None)
|
||||
assert out["items"] == [] and out["note"]
|
||||
|
||||
|
||||
def test_seal_is_a_detached_cades_over_the_bytes(signer_env, monkeypatch):
|
||||
audited = []
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
|
||||
data = b'{"manifest": 1}'
|
||||
der = evidence.seal(None, SimpleNamespace(id=READER), data)
|
||||
signed = cms.ContentInfo.load(der)["content"]
|
||||
assert signed["encap_content_info"]["content"].native is None # detached
|
||||
attrs = {a["type"].native: a["values"][0].native
|
||||
for a in signed["signer_infos"][0]["signed_attrs"]}
|
||||
assert attrs["message_digest"] == hashlib.sha256(data).digest()
|
||||
assert "signing_certificate_v2" in attrs # CAdES
|
||||
assert audited[0]["action"] == "seal.issued"
|
||||
assert audited[0]["detail"] == f"sha256 {hashlib.sha256(data).hexdigest()}"
|
||||
|
||||
|
||||
def test_seal_refuses_everybody_else():
|
||||
with pytest.raises(NotFoundError):
|
||||
evidence.seal(None, SimpleNamespace(id=uuid.uuid4()), b"x")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def as_user(monkeypatch):
|
||||
def login(user_id):
|
||||
user = SimpleNamespace(id=user_id, is_admin=False, is_active=True)
|
||||
cred = SimpleNamespace(scope="read", id=uuid.uuid4(), kind="app_token")
|
||||
monkeypatch.setattr(auth_service, "resolve_session_full", lambda db, t: (user, cred))
|
||||
monkeypatch.setattr(moderation_service, "assert_may_use", lambda db, u: None)
|
||||
return TestClient(main.app, headers={"Authorization": "Bearer t"})
|
||||
main.app.dependency_overrides[get_db] = lambda: SimpleNamespace(commit=lambda: None)
|
||||
yield login
|
||||
main.app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, path, status", [
|
||||
("GET", "/api/v1/requests", 404), ("GET", "/api/v1/auth/me", 404),
|
||||
("POST", "/api/v1/verify", 404), ("GET", f"/api/v1/evidence?document_id={DOC}", 200),
|
||||
("POST", "/api/v1/seal", 200)])
|
||||
def test_technical_account_reaches_only_its_routes(as_user, monkeypatch, method, path, status):
|
||||
monkeypatch.setattr(evidence, "for_document", lambda db, u, d, token: {"items": []})
|
||||
monkeypatch.setattr(evidence, "seal", lambda db, u, data, ip: b"sig")
|
||||
r = as_user(READER).request(method, path, content=b"x")
|
||||
assert r.status_code == status, r.text
|
||||
if path.endswith("/seal"):
|
||||
assert r.headers["content-type"] == "application/pkcs7-signature"
|
||||
|
||||
|
||||
def test_seal_is_404_for_a_person(as_user):
|
||||
assert as_user(uuid.uuid4()).post("/api/v1/seal", content=b"x").status_code == 404
|
||||
|
||||
|
||||
def test_seal_route_signs_for_real(as_user, signer_env, monkeypatch):
|
||||
"""Parafa#9: the async route used to call asyncio.run inside its own loop - a 500 every time.
|
||||
No monkeypatch of `seal` here: the real signer, through the real route."""
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: None)
|
||||
data = b'{"manifest": 1}'
|
||||
r = as_user(READER).post("/api/v1/seal", content=data)
|
||||
assert r.status_code == 200, r.text
|
||||
signed = cms.ContentInfo.load(r.content)["content"]
|
||||
attrs = {a["type"].native: a["values"][0].native
|
||||
for a in signed["signer_infos"][0]["signed_attrs"]}
|
||||
assert attrs["message_digest"] == hashlib.sha256(data).digest()
|
||||
|
||||
|
||||
def test_one_failing_report_keeps_the_listing(two_rows, monkeypatch):
|
||||
"""Parafa#9: one row that cannot be verified used to fail the whole listing (422 / 409)."""
|
||||
rows, _audited = two_rows
|
||||
|
||||
def report(row):
|
||||
if row is rows[1]:
|
||||
raise signing.ConflictError("Trwają inne weryfikacje; spróbuj za chwilę.",
|
||||
{"code": "verify_busy"})
|
||||
return b"{}"
|
||||
monkeypatch.setattr(evidence, "_report", report)
|
||||
out = evidence.for_document(None, SimpleNamespace(id=READER), DOC, token="t")
|
||||
kinds = [(i["source_id"], i["kind"]) for i in out["items"]]
|
||||
assert kinds == [(str(rows[0].id), "signed_pdf"), (str(rows[0].id), "verification_report"),
|
||||
(str(rows[1].id), "signed_pdf")]
|
||||
assert str(rows[1].id) in out["note"] and "weryfikacji" in out["note"]
|
||||
|
||||
|
||||
def test_the_archive_verifies_what_parafa_stores_and_waits_for_a_slot(monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def bounded(data, *, max_bytes, wait):
|
||||
seen.update(max_bytes=max_bytes, wait=wait)
|
||||
return {"count": 0}
|
||||
monkeypatch.setattr(signing, "_verify_bounded", bounded)
|
||||
monkeypatch.setattr(signing, "files", lambda: SimpleNamespace(read=lambda ref: b"%PDF"))
|
||||
monkeypatch.setattr(signing, "signed_ref", lambda row: "ref")
|
||||
evidence._report(_row())
|
||||
assert seen == {"max_bytes": evidence.MAX_FILE_BYTES, "wait": evidence.VERIFY_WAIT_SECONDS}
|
||||
|
||||
|
||||
def test_verify_bounded_waits_only_when_asked(monkeypatch):
|
||||
monkeypatch.setattr(signing.pades, "verify", lambda data: {"ok": True})
|
||||
sem = signing.threading.BoundedSemaphore(1)
|
||||
monkeypatch.setattr(signing, "_VERIFYING", sem)
|
||||
sem.acquire()
|
||||
with pytest.raises(signing.ConflictError):
|
||||
signing._verify_bounded(b"x")
|
||||
with pytest.raises(signing.ConflictError):
|
||||
signing._verify_bounded(b"x", wait=0.05)
|
||||
sem.release()
|
||||
assert signing._verify_bounded(b"x", wait=0.05) == {"ok": True}
|
||||
with pytest.raises(signing.ValidationError):
|
||||
signing._verify_bounded(b"xx", max_bytes=1)
|
||||
@@ -214,7 +214,8 @@ def test_a_document_that_cannot_be_signed_is_failed_and_retryable(admin_client,
|
||||
|
||||
|
||||
class _FakeGalena:
|
||||
"""Galena's three calls Parafa makes, in memory: file-info, raw at a commit, upload."""
|
||||
"""Galena's calls Parafa makes, in memory: file-info, raw at a commit, upload, and the reader's
|
||||
roles on the documents (`POST /projects/roles`, which `galena_readable` asks before a list)."""
|
||||
|
||||
service = "Galena"
|
||||
|
||||
@@ -233,6 +234,10 @@ class _FakeGalena:
|
||||
{"exists": True, "last_commit": {"sha": self.head}}).encode())
|
||||
if path.endswith("/raw"):
|
||||
return ModuleResponse(200, {}, self.versions[params["ref"]])
|
||||
if path == "/projects/roles":
|
||||
# The test's person may read every document they ask about.
|
||||
return ModuleResponse(200, {}, _json.dumps(
|
||||
{p: "manager" for p in (json or {}).get("project_ids", [])}).encode())
|
||||
if path.endswith("/upload"):
|
||||
assert b'name="dest"' in body
|
||||
part = body.split(b'filename="', 1)[1].split(b"\r\n\r\n", 1)[1]
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Completing, sending and withdrawing a request through a manual provider, end to end over fakes
|
||||
(no database, no Galena, no pyHanko). DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from dredd_core.document_ref import FileRef
|
||||
from dredd_core.errors import AuthorizationError
|
||||
|
||||
from app.errors import ConflictError, ValidationError
|
||||
from app.models import SigningRequest
|
||||
from app.services import providers, signing
|
||||
|
||||
ORIGINAL = b"%PDF-1.7\n...the document...\n%%EOF\n"
|
||||
SIGNED = ORIGINAL + b"...an incremental update with the signature...\n%%EOF\n"
|
||||
REPORT = {"count": 1, "signatures": [{"intact": True, "valid": True, "trusted": False,
|
||||
"coverage": "ENTIRE_FILE", "signer": "CN=Jan"}]}
|
||||
MODERATOR = types.SimpleNamespace(id=uuid.uuid4(), is_admin=True, full_name="M", email="m@x")
|
||||
OWNER = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False, full_name="O", email="o@x")
|
||||
|
||||
|
||||
class _Db:
|
||||
"""Just enough of a Session: `get` by primary key, the row lock, and transaction calls."""
|
||||
|
||||
def __init__(self, row, on_lock=None):
|
||||
self.row, self.on_lock, self.calls = row, on_lock, []
|
||||
|
||||
def get(self, model, _id):
|
||||
return self.row if model is SigningRequest else None
|
||||
|
||||
def scalars(self, _stmt):
|
||||
if self.on_lock:
|
||||
self.on_lock(self.row)
|
||||
return types.SimpleNamespace(all=lambda: [self.row])
|
||||
|
||||
def flush(self):
|
||||
self.calls.append("flush")
|
||||
|
||||
def commit(self):
|
||||
self.calls.append("commit")
|
||||
|
||||
def rollback(self):
|
||||
self.calls.append("rollback")
|
||||
|
||||
|
||||
class _Files:
|
||||
def __init__(self):
|
||||
self.saved, self.deleted = [], []
|
||||
|
||||
def save(self, data, name):
|
||||
ref = FileRef(file_id=uuid.uuid4(), sha256="b" * 64, size=len(data), name=name)
|
||||
self.saved.append(ref)
|
||||
return ref
|
||||
|
||||
def delete(self, file_id):
|
||||
self.deleted.append(file_id)
|
||||
|
||||
|
||||
def _row(status="sent", provider="signudoc"):
|
||||
row = SigningRequest(id=uuid.uuid4(), title="Umowa", status=status, owner_id=OWNER.id,
|
||||
provider=provider)
|
||||
row.set_ref(FileRef(file_id=uuid.uuid4(), sha256="a" * 64, size=len(ORIGINAL), name="u.pdf"))
|
||||
return row
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(monkeypatch):
|
||||
"""Fakes for everything outside the service; returns the recorded side effects."""
|
||||
monkeypatch.setattr(providers.get_settings(), "signing_providers", "local,signudoc")
|
||||
store, audits, events = _Files(), [], []
|
||||
monkeypatch.setattr(signing, "files", lambda: store)
|
||||
monkeypatch.setattr(signing, "galena", lambda: None)
|
||||
monkeypatch.setattr(signing.document_ref, "read", lambda *a, **k: ORIGINAL)
|
||||
monkeypatch.setattr(signing.pades, "check_pdf", lambda *a: None)
|
||||
monkeypatch.setattr(signing.pades, "verify", lambda data: REPORT)
|
||||
monkeypatch.setattr(signing.audit, "record", lambda db, **k: audits.append(k["action"]))
|
||||
monkeypatch.setattr(signing.core_events, "emit", lambda db, kind, **k: events.append(kind))
|
||||
return types.SimpleNamespace(store=store, audits=audits, events=events)
|
||||
|
||||
|
||||
def _complete(db, actor=MODERATOR, data=SIGNED):
|
||||
return signing.complete_manual(db, actor=actor, request_id=db.row.id, data=data, name="s.pdf",
|
||||
token="tok")
|
||||
|
||||
|
||||
def test_a_moderator_completes_a_sent_request(world):
|
||||
db = _Db(_row())
|
||||
out = _complete(db)
|
||||
row = db.row
|
||||
assert (row.status, row.provider, row.signer_subject) == ("signed", "signudoc", "CN=Jan")
|
||||
assert row.signed_file_id == world.store.saved[0].file_id and not world.store.deleted
|
||||
assert world.audits == ["signing.signed"] and world.events == [signing.DOCUMENT_SIGNED]
|
||||
assert db.calls[-1] == "commit"
|
||||
assert out["status"] == "signed" and not out["can_complete"]
|
||||
|
||||
|
||||
def test_the_owner_may_not_complete_it(world):
|
||||
db = _Db(_row())
|
||||
with pytest.raises(AuthorizationError):
|
||||
_complete(db, actor=OWNER)
|
||||
assert db.row.status == "sent" and not world.store.saved
|
||||
|
||||
|
||||
def test_losing_the_race_is_a_409_and_stores_nothing(world):
|
||||
db = _Db(_row(), on_lock=lambda row: setattr(row, "status", "draft")) # withdrawn meanwhile
|
||||
with pytest.raises(ConflictError) as err:
|
||||
_complete(db)
|
||||
assert err.value.extra["code"] == "not_sent" and not world.store.saved
|
||||
|
||||
|
||||
def test_a_failure_after_storing_deletes_the_file_again(world, monkeypatch):
|
||||
def boom(db, **k):
|
||||
raise RuntimeError("audit down")
|
||||
monkeypatch.setattr(signing.audit, "record", boom)
|
||||
db = _Db(_row())
|
||||
with pytest.raises(RuntimeError):
|
||||
_complete(db)
|
||||
assert world.store.deleted == [world.store.saved[0].file_id] and "rollback" in db.calls
|
||||
|
||||
|
||||
def test_a_file_changed_after_its_last_signature_is_refused(world, monkeypatch):
|
||||
report = {"count": 1, "signatures": [dict(REPORT["signatures"][0], coverage="ENTIRE_REVISION")]}
|
||||
monkeypatch.setattr(signing.pades, "verify", lambda data: report)
|
||||
db = _Db(_row())
|
||||
with pytest.raises(ValidationError) as err:
|
||||
_complete(db, data=SIGNED + b"an unsigned update\n%%EOF\n")
|
||||
assert err.value.extra["code"] == "signed_upload_refused" and db.row.status == "sent"
|
||||
|
||||
|
||||
def test_send_with_a_provider_that_signs_at_once_is_a_422(world):
|
||||
with pytest.raises(ValidationError) as err:
|
||||
signing.send(_Db(_row("draft", None)), actor=OWNER, request_id=uuid.uuid4(),
|
||||
provider="local", token="tok")
|
||||
assert err.value.extra["code"] == "provider_not_manual"
|
||||
|
||||
|
||||
def test_send_hands_a_draft_over_and_withdraw_takes_it_back(world):
|
||||
db = _Db(_row("draft", None))
|
||||
out = signing.send(db, actor=OWNER, request_id=db.row.id, provider="signudoc", token="tok")
|
||||
assert (db.row.status, db.row.provider) == ("sent", "signudoc")
|
||||
assert out["can_withdraw"] and not out["can_complete"] # the owner hands over, not signs
|
||||
signing.withdraw(db, actor=OWNER, request_id=db.row.id, token="tok")
|
||||
assert (db.row.status, db.row.provider) == ("draft", None)
|
||||
assert world.audits == ["signing.sent", "signing.withdrawn"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["draft", "failed", "signed"])
|
||||
def test_withdraw_from_anything_but_sent_is_a_409(world, status):
|
||||
db = _Db(_row(status, None))
|
||||
with pytest.raises(ConflictError) as err:
|
||||
signing.withdraw(db, actor=OWNER, request_id=db.row.id, token="tok")
|
||||
assert err.value.extra["code"] == "not_sent"
|
||||
|
||||
|
||||
def test_sign_is_refused_when_the_seal_is_not_offered(world, monkeypatch):
|
||||
monkeypatch.setattr(providers.get_settings(), "signing_providers", "signudoc")
|
||||
db = _Db(_row("draft", None))
|
||||
with pytest.raises(ValidationError) as err:
|
||||
signing.sign(db, actor=MODERATOR, request_id=db.row.id, token="tok")
|
||||
assert err.value.extra["code"] == "provider_unknown" and db.row.status == "draft"
|
||||
|
||||
|
||||
def test_the_flags_are_read_once_per_list(world, monkeypatch):
|
||||
calls = []
|
||||
real = providers.enabled
|
||||
monkeypatch.setattr(providers, "enabled", lambda: calls.append(1) or real())
|
||||
rows = [_row("draft", None), _row("sent")]
|
||||
monkeypatch.setattr(signing, "_rows", lambda *a, **k: rows)
|
||||
out = signing.list_requests(_Db(rows[0]), MODERATOR, token="tok")
|
||||
assert len(calls) == 1
|
||||
assert [(r["can_sign"], r["can_send"], r["can_complete"]) for r in out] == [
|
||||
(True, True, False), (False, False, True)]
|
||||
|
||||
|
||||
def test_counts_are_one_query_and_one_galena_call(world, monkeypatch):
|
||||
doc_ok, doc_gone = uuid.uuid4(), uuid.uuid4()
|
||||
asked = []
|
||||
|
||||
def readable(ids, *, token):
|
||||
asked.append(list(ids))
|
||||
return {doc_ok}
|
||||
monkeypatch.setattr(signing, "galena_readable", readable)
|
||||
rows = [types.SimpleNamespace(status=s, ref_document_id=d) for s, d in [
|
||||
("draft", None), ("sent", doc_ok), ("failed", doc_gone), ("signed", None),
|
||||
("signed", doc_gone)]]
|
||||
db = types.SimpleNamespace(execute=lambda stmt: types.SimpleNamespace(all=lambda: rows))
|
||||
assert signing.counts(db, MODERATOR, token="tok") == {"todo": 2, "signed": 1}
|
||||
assert len(asked) == 1
|
||||
@@ -0,0 +1,42 @@
|
||||
"""A request handed over by Workflow: `#/new?document_id=&path=&version=` opens the new request with
|
||||
the Galena document fixed at the approved commit. Driven in Node with a stubbed DOM
|
||||
(`console_new_from_link.js`): the route, the prefilled and escaped form, and what saving it POSTs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
APP_JS = HERE.parents[1] / "frontend" / "app.js"
|
||||
NODE = shutil.which("node") or next(
|
||||
(str(p) for p in (pathlib.Path("C:/Program Files/nodejs/node.exe"),) if p.exists()), None)
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="needs Node")
|
||||
|
||||
|
||||
def _open(hash_: str) -> dict:
|
||||
out = subprocess.run([NODE, str(HERE / "console_new_from_link.js"), str(APP_JS), hash_],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=30, check=True)
|
||||
return json.loads(out.stdout)
|
||||
|
||||
|
||||
def test_the_new_route_opens_the_form_prefilled_and_escaped() -> None:
|
||||
out = _open("#/new?document_id=d-1&path=umowy%2Fa%22b.pdf&version=abc123&title=%3Cb%3EUmowa")
|
||||
assert out["title"] == "Nowy wniosek"
|
||||
body = out["body"]
|
||||
assert 'id="nqDoc" placeholder="UUID" value="d-1" readonly' in body
|
||||
assert 'value="umowy/a"b.pdf" readonly' in body # escaped, and fixed
|
||||
assert 'id="nqVersion" value="abc123"' in body
|
||||
assert "<b>Umowa" in body and "<b>" not in body
|
||||
|
||||
|
||||
def test_saving_it_pins_the_approved_version() -> None:
|
||||
out = _open("#/new?document_id=d-1&path=umowy%2Fa.pdf&version=abc123&title=Umowa")
|
||||
post = out["calls"][0]
|
||||
assert (post["method"], post["path"]) == ("POST", "/requests/document")
|
||||
assert post["body"] == {"document_id": "d-1", "path": "umowy/a.pdf", "version": "abc123",
|
||||
"title": "Umowa", "reason": None, "note": None}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Parafa as a gateway to signature providers. DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.models.signing import STATUSES
|
||||
from app.services import providers, signing
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
ORIGINAL = b"%PDF-1.7\n...the document...\n%%EOF\n"
|
||||
SIGNED = ORIGINAL + b"...an incremental update with the signature...\n%%EOF\n"
|
||||
GOOD = {"count": 1, "signatures": [{"intact": True, "valid": True, "signer": "CN=Jan",
|
||||
"coverage": "ENTIRE_FILE"}]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offered(monkeypatch):
|
||||
def set_(value):
|
||||
monkeypatch.setattr(providers.get_settings(), "signing_providers", value)
|
||||
return set_
|
||||
|
||||
|
||||
def test_both_by_default_the_seal_first(offered):
|
||||
offered("local,signudoc")
|
||||
assert [p.key for p in providers.enabled()] == ["local", "signudoc"]
|
||||
assert providers.get(None).key == "local" and providers.get("signudoc").manual
|
||||
|
||||
|
||||
def test_unknown_names_are_ignored_and_nothing_falls_back_to_the_seal(offered):
|
||||
offered("nope, ")
|
||||
assert [p.key for p in providers.enabled()] == ["local"]
|
||||
offered("signudoc")
|
||||
with pytest.raises(ValidationError):
|
||||
providers.get("local")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("signed, report, refused", [
|
||||
(SIGNED, GOOD, None),
|
||||
(b"%PDF-1.7\nanother document\n" + SIGNED, GOOD, "oryginału"), # not this document
|
||||
(ORIGINAL, GOOD, "oryginału"), # nothing was added
|
||||
(SIGNED, {"count": 0, "signatures": []}, "nie ma podpisu"),
|
||||
(SIGNED, {"count": 1, "signatures": [{"intact": False}]}, "uszkodzony"),
|
||||
# an unsigned incremental update after the last signature
|
||||
(SIGNED, {"count": 1, "signatures": [{"intact": True, "coverage": "ENTIRE_REVISION"}]},
|
||||
"Po ostatnim podpisie"),
|
||||
(SIGNED, {"count": 2, "signatures": [{"intact": True, "coverage": "ENTIRE_REVISION"},
|
||||
{"intact": True, "coverage": "ENTIRE_FILE"}]}, None),
|
||||
])
|
||||
def test_an_upload_must_be_this_document_signed_and_intact(signed, report, refused):
|
||||
out = signing.check_signed_upload(ORIGINAL, signed, report)
|
||||
assert out is None if refused is None else refused in out
|
||||
|
||||
|
||||
def test_an_untrusted_signer_is_reported_not_refused():
|
||||
report = {"count": 1, "signatures": [{"intact": True, "valid": True, "trusted": False,
|
||||
"coverage": "ENTIRE_FILE"}]}
|
||||
assert signing.check_signed_upload(ORIGINAL, SIGNED, report) is None
|
||||
|
||||
|
||||
def test_sent_is_a_status_still_to_sign():
|
||||
assert "sent" in STATUSES and "sent" in signing.VIEWS["todo"]
|
||||
|
||||
|
||||
def test_0006_adds_the_column_and_widens_the_check_idempotently():
|
||||
path = BACKEND / "alembic" / "versions" / "0006_signing_providers.py"
|
||||
spec = importlib.util.spec_from_file_location("_rev_0006", path)
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0006", "0005")
|
||||
assert rev.NEW == STATUSES
|
||||
source = path.read_text(encoding="utf-8")
|
||||
assert "ADD COLUMN IF NOT EXISTS provider text" in source
|
||||
assert "DROP CONSTRAINT IF EXISTS" in source
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The three medium findings of the Atrium#53 review, stage 3. DB-free.
|
||||
"""Three security rules of the signing service. DB-free.
|
||||
|
||||
1. A request on a Galena document is readable only while Galena lets the person read the document.
|
||||
2. A failed signature never shows the exception's own text to the requester.
|
||||
@@ -70,7 +70,7 @@ def test_a_request_on_a_document_galena_no_longer_shows_is_a_404(monkeypatch):
|
||||
|
||||
|
||||
def test_like_wildcards_are_what_the_person_typed():
|
||||
assert signing._literal_like("50%_a\b") == "50\%\_a\\b"
|
||||
assert signing._literal_like(r"50%_a\b") == r"50\%\_a\\b"
|
||||
|
||||
|
||||
def test_verify_refuses_a_file_over_the_cap():
|
||||
@@ -86,7 +86,19 @@ def test_a_third_verification_at_once_is_told_to_wait(monkeypatch):
|
||||
assert err.value.extra["code"] == "verify_busy"
|
||||
|
||||
|
||||
def test_a_failed_signature_shows_a_reference_not_the_exception():
|
||||
import inspect
|
||||
source = inspect.getsource(signing.sign)
|
||||
assert "{exc}" not in source and "log.exception" in source
|
||||
def test_a_failed_signature_shows_a_reference_not_the_exception(monkeypatch):
|
||||
from tests.test_manual_signing_unit import MODERATOR, _Db, _row
|
||||
|
||||
def leak(*_a, **_k):
|
||||
raise RuntimeError("C:/srv/secret/internal-url")
|
||||
recorded = []
|
||||
monkeypatch.setattr(signing.providers.get_settings(), "signing_providers", "local")
|
||||
monkeypatch.setattr(pades, "signer", lambda: object())
|
||||
monkeypatch.setattr(signing.document_ref, "read", leak)
|
||||
monkeypatch.setattr(signing, "galena", lambda: None)
|
||||
monkeypatch.setattr(signing, "_fail", lambda db, row, actor, message, ip: recorded.append(message))
|
||||
db = _Db(_row("draft", None))
|
||||
with pytest.raises(ConflictError) as err:
|
||||
signing.sign(db, actor=MODERATOR, request_id=db.row.id, token="tok")
|
||||
assert "secret" not in err.value.detail and "secret" not in recorded[0]
|
||||
assert "błąd" in recorded[0] and err.value.extra["code"] == "signing_failed"
|
||||
|
||||
@@ -137,9 +137,8 @@ def test_event_payload_is_identifiers_only():
|
||||
|
||||
|
||||
def test_stats_answer_the_contract(monkeypatch):
|
||||
monkeypatch.setattr(signing, "count",
|
||||
lambda db, user, view, token=None: {"todo": 3, "signed": 5}[view])
|
||||
body = signing.module_stats(None, None)
|
||||
monkeypatch.setattr(signing, "counts", lambda db, user, token: {"todo": 3, "signed": 5})
|
||||
body = signing.module_stats(None, None, token="tok")
|
||||
stats_contract.validate_response(body)
|
||||
assert [(t["key"], t["count"], t["link"]) for t in body["tiles"]] == [
|
||||
("to_sign", 3, "todo"), ("signed", 5, "signed")]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Parafa 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 Parafa has schema
|
||||
|
||||
+1
-1
@@ -67,6 +67,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
|
||||
|
||||
+96
-7
@@ -230,6 +230,7 @@ const I18N = {
|
||||
'Zweryfikuj podpis': 'Verify a signature',
|
||||
'Zweryfikuj': 'Verify',
|
||||
'Nowy wniosek': 'New request',
|
||||
'dokument z Galeny, wersja zatwierdzona w obiegu': 'a Galena document, the version approved in the workflow',
|
||||
'Brak wniosków.': 'No requests.',
|
||||
'Wnioski': 'Requests',
|
||||
'Tytuł': 'Title',
|
||||
@@ -239,6 +240,14 @@ const I18N = {
|
||||
'Zmieniono': 'Changed',
|
||||
'do podpisu': 'to sign',
|
||||
'podpisany': 'signed',
|
||||
'u dostawcy': 'with the provider',
|
||||
'Przekaż do podpisu': 'Hand over for signing',
|
||||
'Wgraj podpisany plik': 'Upload the signed file',
|
||||
'Wycofaj': 'Withdraw',
|
||||
'Wniosek czeka na podpis u dostawcy': 'The request is waiting to be signed at the provider',
|
||||
'Pobierz oryginał, podpisz go u dostawcy i wgraj podpisany PDF. Parafa sprawdzi, że to podpisana wersja tego dokumentu.': 'Download the original, sign it at the provider and upload the signed PDF. Parafa checks that it is the signed version of this document.',
|
||||
'Dostawca podpisu': 'Signature provider',
|
||||
'Podpisany PDF': 'Signed PDF',
|
||||
'nieudany': 'failed',
|
||||
'plik': 'file',
|
||||
'Oryginał': 'Original',
|
||||
@@ -501,6 +510,7 @@ async function router() {
|
||||
else if (seg[0] === 'requests' && seg[1]) await viewRequest(C, seg[1]);
|
||||
else if (seg[0] === 'todo' || seg[0] === 'signed') await viewRequests(C, seg[0], q);
|
||||
else if (seg[0] === 'verify') await viewVerify(C);
|
||||
else if (seg[0] === 'new') { await viewDashboard(C); openRequestNew(q); }
|
||||
else if (seg[0] === 'admin') await viewAdmin(C);
|
||||
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
|
||||
} catch (ex) {
|
||||
@@ -536,7 +546,7 @@ async function viewDashboard(C) {
|
||||
+ `<div class="card" style="margin-top:14px"><h3>Do podpisu<span class="n">${(d.recent || []).length}</span></h3>${requestTable(d.recent || [])}</div>`;
|
||||
}
|
||||
|
||||
const STATUS_LABEL = { draft: 'do podpisu', signed: 'podpisany', failed: 'nieudany' };
|
||||
const STATUS_LABEL = { draft: 'do podpisu', sent: 'u dostawcy', signed: 'podpisany', failed: 'nieudany' };
|
||||
|
||||
function statusChip(s) {
|
||||
const cls = s === 'signed' ? 'ok' : (s === 'failed' ? 'err' : '');
|
||||
@@ -588,13 +598,18 @@ async function viewRequest(C, id) {
|
||||
`<button class="btn" onclick="downloadFile('/requests/${rid}/original')">${svg(ICN.download)}Oryginał</button>`
|
||||
+ (s ? `<button class="btn" onclick="downloadFile('/requests/${rid}/signed')">${svg(ICN.download)}Podpisany plik</button>` : '')
|
||||
+ (s ? `<button class="btn" onclick="verifyRequest('${rid}')">${svg(ICN.shield)}Zweryfikuj</button>` : '')
|
||||
+ (r.can_send ? `<button class="btn" onclick="openSend('${rid}')">${svg(ICN.signature)}Przekaż do podpisu</button>` : '')
|
||||
+ (r.can_withdraw ? `<button class="btn" onclick="withdrawRequest('${rid}')">Wycofaj</button>` : '')
|
||||
+ (r.can_complete ? `<button class="btn primary" onclick="openSignedUpload('${rid}')">${svg(ICN.signature)}Wgraj podpisany plik</button>` : '')
|
||||
+ (r.can_sign ? `<button class="btn primary" onclick="confirmSign('${rid}')">${svg(ICN.signature)}Podpisz</button>` : ''))
|
||||
+ (r.awaiting_upload ? `<div class="banner warn"><strong>Wniosek czeka na podpis u dostawcy</strong> <span data-no-i18n>(${esc(r.provider || '')})</span>. <span>Pobierz oryginał, podpisz go u dostawcy; podpisany PDF wgrywa moderator. Parafa sprawdzi, że to podpisana wersja tego dokumentu.</span></div>` : '')
|
||||
+ (r.status === 'failed' && r.error ? `<div class="banner err"><span>Ostatnia próba podpisu nie powiodła się:</span> ${esc(r.error)}</div>` : '')
|
||||
+ `<div class="card"><div class="grid3">
|
||||
${field('Status', STATUS_LABEL[r.status] || r.status)}
|
||||
${field('Źródło', (r.on_galena ? 'Galena' : _tr('plik')) + ': ' + (r.on_galena ? r.ref.path : r.name))}
|
||||
${field('Wnioskodawca', r.owner_name)}
|
||||
${field('Powód podpisu', r.reason)}
|
||||
<div><div class="tiny faint">Kontrahent</div><div><span data-no-i18n>${esc(r.counterparty ? r.counterparty.name : '—')}</span>${r.mine || isModerator() ? ` <button class="btn sm" onclick="openRequestParty('${rid}')">Zmień</button>` : ''}</div></div>
|
||||
${field('Utworzono', fmtDateTime(r.created_at))}
|
||||
${field('SHA-256', r.ref.sha256)}
|
||||
</div>
|
||||
@@ -611,6 +626,73 @@ async function viewRequest(C, id) {
|
||||
+ '<div id="verifyOut"></div>';
|
||||
}
|
||||
|
||||
/* The contract's party from the platform's register (spec 2026-11-25 part A): read only here, a
|
||||
reference for the archive. The signers are still the certificate's subject alone. */
|
||||
function openRequestParty(id) {
|
||||
modal('Kontrahent', '',
|
||||
`<label class="field">Szukaj w kartotece (nazwa, NIP, KRS)<input id="rpQ" maxlength="200" oninput="requestPartySearch('${esc(id)}', this.value)" /></label>
|
||||
<div id="rpFound" style="margin-top:8px"></div>`,
|
||||
`<button class="btn" onclick="requestPartySave('${esc(id)}', null)">Usuń powiązanie</button><button class="btn" onclick="closeModal()">Zamknij</button>`);
|
||||
}
|
||||
let _rpTimer = null;
|
||||
function requestPartySearch(id, q) {
|
||||
clearTimeout(_rpTimer);
|
||||
_rpTimer = setTimeout(async () => {
|
||||
const el = $('rpFound'); if (!el) return;
|
||||
if (!q.trim()) { el.innerHTML = ''; return; }
|
||||
let rows; try { rows = await api('GET', '/counterparties?q=' + encodeURIComponent(q.trim())); } catch (e) { modalError(e.message); return; }
|
||||
el.innerHTML = rows.length ? rows.map((c) => `<div style="display:flex;gap:8px;align-items:center;margin-bottom:4px"><span style="flex:1" data-no-i18n>${esc(c.name)}${c.nip ? ' · NIP ' + esc(c.nip) : ''}</span><button class="btn sm" data-id="${esc(c.id)}" onclick="requestPartySave('${esc(id)}', this.dataset.id)">Wybierz</button></div>`).join('')
|
||||
: '<div class="empty">Nie ma takiego kontrahenta w kartotece.</div>';
|
||||
}, 250);
|
||||
}
|
||||
async function requestPartySave(id, cid) {
|
||||
try {
|
||||
await api('PUT', '/requests/' + encodeURIComponent(id) + '/counterparty', { counterparty_id: cid });
|
||||
closeModal(); viewRequest($('content'), id);
|
||||
} catch (e) { modalError(e.message); }
|
||||
}
|
||||
|
||||
/* An external provider by hand (SignuDoc in the Start edition): hand over, then upload the result. */
|
||||
async function openSend(id) {
|
||||
const manual = (await api('GET', '/providers')).filter((p) => p.manual);
|
||||
modal('Przekaż do podpisu', '',
|
||||
`<label class="field">Dostawca podpisu<select id="spProvider">${manual.map((p) =>
|
||||
`<option value="${esc(p.key)}">${esc(p.label)}</option>`).join('')}</select></label>`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn primary" onclick="doSend('${esc(id)}')">Przekaż do podpisu</button>`);
|
||||
}
|
||||
function doSend(id) {
|
||||
guard(async () => {
|
||||
try {
|
||||
await api('POST', '/requests/' + encodeURIComponent(id) + '/send', { provider: $('spProvider').value });
|
||||
closeModal();
|
||||
} finally { await router(); }
|
||||
});
|
||||
}
|
||||
function withdrawRequest(id) {
|
||||
guard(async () => {
|
||||
try { await api('POST', '/requests/' + encodeURIComponent(id) + '/withdraw'); } finally { await router(); }
|
||||
});
|
||||
}
|
||||
function openSignedUpload(id) {
|
||||
modal('Wgraj podpisany plik', '',
|
||||
`<label class="field">Podpisany PDF<input id="spFile" type="file" accept="application/pdf,.pdf" /></label>`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn primary" onclick="doSignedUpload('${esc(id)}')">Wgraj podpisany plik</button>`);
|
||||
}
|
||||
function doSignedUpload(id) {
|
||||
guard(async () => {
|
||||
const f = $('spFile').files[0];
|
||||
if (!f) throw new Error('Wybierz plik PDF.');
|
||||
const form = new FormData();
|
||||
form.append('file', f, f.name);
|
||||
await apiForm('/requests/' + encodeURIComponent(id) + '/signed-upload', form);
|
||||
closeModal();
|
||||
toast('Podpisano.');
|
||||
await router();
|
||||
});
|
||||
}
|
||||
|
||||
function confirmSign(id) {
|
||||
modal('Podpisz', '',
|
||||
'<div class="banner warn">Plik zostanie podpisany certyfikatem operatora (PAdES). Podpisu nie da się wycofać.</div>',
|
||||
@@ -727,16 +809,22 @@ async function viewVerify(C) {
|
||||
}
|
||||
|
||||
/* ── a new request ──────────────────────────────────────────────────────── */
|
||||
function openRequestNew() {
|
||||
/* `pre`: a document handed over by another module (Workflow's "Wyślij do podpisu" on an approved run):
|
||||
`#/new?document_id=…&path=…&version=<commit>&title=…`. The version is the commit the run
|
||||
approved, so exactly what was approved is pinned and signed. */
|
||||
function openRequestNew(pre = {}) {
|
||||
const fixed = !!(pre.document_id && pre.path);
|
||||
const ro = fixed ? ' readonly' : '';
|
||||
const galena = state.galena
|
||||
? `<div class="tiny faint" style="margin-top:14px">albo dokument z Galeny</div>
|
||||
<label class="field" style="margin-top:6px">Identyfikator projektu<input id="nqDoc" placeholder="UUID" /></label>
|
||||
<label class="field" style="margin-top:8px">Ścieżka pliku<input id="nqPath" placeholder="umowy/umowa.pdf" /></label>`
|
||||
? `<div class="tiny faint" style="margin-top:14px">${fixed ? 'dokument z Galeny, wersja zatwierdzona w obiegu' : 'albo dokument z Galeny'}</div>
|
||||
<label class="field" style="margin-top:6px">Identyfikator projektu<input id="nqDoc" placeholder="UUID" value="${esc(pre.document_id || '')}"${ro} /></label>
|
||||
<label class="field" style="margin-top:8px">Ścieżka pliku<input id="nqPath" placeholder="umowy/umowa.pdf" value="${esc(pre.path || '')}"${ro} /></label>
|
||||
<input type="hidden" id="nqVersion" value="${esc(pre.version || '')}" />`
|
||||
: '';
|
||||
modal('Nowy wniosek', 'Tylko pliki PDF.',
|
||||
`<label class="field">Plik PDF<input type="file" id="nqFile" accept=".pdf,application/pdf" /></label>
|
||||
${galena}
|
||||
<label class="field" style="margin-top:12px">Tytuł<input id="nqTitle" maxlength="200" /></label>
|
||||
<label class="field" style="margin-top:12px">Tytuł<input id="nqTitle" maxlength="200" value="${esc(pre.title || '')}" /></label>
|
||||
<label class="field" style="margin-top:12px">Powód podpisu<input id="nqReason" maxlength="200" /></label>
|
||||
<label class="field" style="margin-top:12px">Notatka<textarea id="nqNote"></textarea></label>`,
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
@@ -759,7 +847,8 @@ function saveRequestNew() {
|
||||
if (note) form.append('note', note);
|
||||
r = await apiForm('/requests/upload', form);
|
||||
} else if (doc) {
|
||||
r = await api('POST', '/requests/document', { document_id: doc, path: $('nqPath').value.trim(), title, reason, note });
|
||||
const version = ($('nqVersion') && $('nqVersion').value) || undefined;
|
||||
r = await api('POST', '/requests/document', { document_id: doc, path: $('nqPath').value.trim(), version, title, reason, note });
|
||||
} else {
|
||||
throw new Error('Wybierz plik PDF.');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user