chore: strip the signing domain from the Parafa skeleton

Removes the PAdES signing module: models/routers/services (signing, pades),
alembic 0005_signing, tests/pki.py and test_signing_unit.py, pyhanko, the
signer mount and SIGNING_* settings, and the console's signing screens.

- GET /stats keeps the stats contract with tiles `inbox` and `running`
  at 0 until the run lists exist; GET /dashboard is gone.
- Console: sign-in, users, administration and an empty main screen. The
  search palette went too: it only searched signing requests.
- GALENA_BASE_URL stays (unused) for the Galena interface.
- dredd_core.events stays imported; the workflow migration takes over
  what 0005_signing did for the event tables.
- Integration suite keeps its floor; the 422 cases now hit user/admin routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tobayah
2026-11-18 18:11:36 +01:00
co-authored by Claude Opus 5.5
parent 67919678bc
commit ad0c7ad81b
22 changed files with 37 additions and 1709 deletions
+2 -17
View File
@@ -73,25 +73,10 @@ DB_LOCAL_HOSTS=
DATA_DIR=/data
# ── Galena (optional) ────────────────────────────────────────────────────────
# Galena's PUBLIC base URL (https://<site>/galena). Empty = no Galena: requests are uploaded PDFs
# only, and a request on a Galena document answers 409 galena_disabled (D9). Set, a request may name
# a Galena document, and its signed PDF is written back there as a new version, with the person's
# own token.
# Galena's PUBLIC base URL (https://<site>/galena), called with the person's own token. Empty = no
# Galena: anything on a Galena document answers 409 galena_disabled.
GALENA_BASE_URL=
# ── The signer (PAdES) ───────────────────────────────────────────────────────
# The operator's certificate + key as ONE PKCS#12 file, mounted read-only (compose mounts
# PARAFA_SIGNER_DIR at /run/parafa-signer). Never commit it; never bake it into an image. The
# passphrase preferably from a secret FILE; SIGNING_PKCS12_PASSPHRASE is the fallback.
# Empty path = signing off: requests and verification work, "Podpisz" answers 409.
SIGNING_PKCS12_PATH=
SIGNING_PKCS12_PASSPHRASE_FILE=
SIGNING_PKCS12_PASSPHRASE=
# PEM bundle of CA certificates a verification trusts (empty = "trusted" is always no).
SIGNING_TRUST_ROOTS=
# /Location in the signature dictionary (optional).
SIGNING_LOCATION=
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — this stack — is STANDALONE: Parafa owns its own
# accounts, has its own sign-in screen and its own Users administration, and the three settings
+1 -2
View File
@@ -14,8 +14,7 @@ data/
.DS_Store
certs/
# The operator's signing material: never in the repo.
signer/
# Key material: never in the repo.
*.p12
*.pfx
.meduza/CONTRACT.md
-110
View File
@@ -1,110 +0,0 @@
"""Signing requests (M6): `signing_request` — and the module-event log Parafa writes
`document.signed` into (dredd-core 0.20.0 `events`).
`0001` builds from the live metadata, so a database created after this revision already has every
table below and this one has nothing to do but the platform step, the event policies and the
grants. It is idempotent and decided by the catalog, as every revision after `0001` must be:
1. **Tables**: each of this revision's tables that is not yet in `current_schema()` is created from
the metadata. The check is the catalog of THIS schema (`to_regclass(own.name)`), never
`checkfirst`, which follows the whole search_path. The receiver's `module_event_cursor` and
`module_event_receipt` are Parafa's own in both shapes (importing `dredd_core.events` registers
them; Parafa receives nothing yet). Standalone the log `module_event` is too.
2. **The event log**. Standalone: `event_policies_sql()` on `current_schema()` (row-level security:
a role inserts only rows whose `source_role` is itself). On the platform (`IDENTITY_SCHEMA` set)
the log is the hub's (`dredd.module_event`, created and granted by the hub's revision); a fresh
platform install still gets a local copy from `0001`, which would shadow the shared one through
the search_path, so it is dropped here — while empty. A row in it would be an event nobody else
ever read, and dropping it silently is the one thing this revision refuses to do.
3. **Runtime grants**, as every table-creating revision ends: the requests on
`NO_DELETE`, the log and the receipts on `APPEND_ONLY` (`app/models/__init__.py`).
No SQL text below carries a percent sign or a colon-name sequence: `op.execute` wraps it in `text()`.
Downgrade drops this revision's own tables when the database is standalone (the log too: events are
a feed, the evidence is the requests and the audit); on the platform it refuses, as `0003` does.
"""
from __future__ import annotations
from dredd_core.events import event_policies_sql
from dredd_core.schema import create_enum_types, 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, Base
revision = "0005"
down_revision = "0004"
branch_labels = None
depends_on = None
#: This revision's own tables, parents before children.
OWN_TABLES = ("signing_request", "module_event_cursor", "module_event_receipt")
EVENT_LOG = "module_event"
def _q(name: str) -> str:
return '"' + name.replace('"', '""') + '"'
def _own(bind) -> str:
return bind.execute(text("SELECT current_schema()")).scalar()
def _exists(bind, schema: str, table: str) -> bool:
return bind.execute(text("SELECT to_regclass(:n) IS NOT NULL"),
{"n": f"{_q(schema)}.{_q(table)}"}).scalar()
def _drop_local_log(bind, own: str) -> None:
if not _exists(bind, own, EVENT_LOG):
return
rows = bind.execute(text(f"SELECT count(*) FROM {_q(own)}.{_q(EVENT_LOG)}")).scalar()
if rows:
raise RuntimeError(
f"signing: {own}.{EVENT_LOG} holds {rows} event(s), written while this schema had a "
"log of its own; on the platform the log is the hub's. Export them if they matter, "
"empty the table, then migrate again. Nothing was dropped.")
op.execute(f"DROP TABLE {_q(own)}.{_q(EVENT_LOG)}")
def _grants() -> str:
return runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
no_delete=NO_DELETE_TABLES)
def upgrade() -> None:
bind = op.get_bind()
settings = get_settings()
if op.get_context().as_sql:
# Offline (`--sql`) there is no catalog to ask: `0001` already rendered every table from
# the metadata, so the rendering of this revision is its grants.
op.execute(_grants())
return
own = _own(bind)
create_enum_types(bind, Base.metadata)
if settings.shares_identity:
_drop_local_log(bind, own)
wanted = OWN_TABLES
else:
wanted = (EVENT_LOG, *OWN_TABLES)
missing = [Base.metadata.tables[name] for name in wanted if not _exists(bind, own, name)]
if missing:
# Unqualified, so it lands in current_schema().
Base.metadata.create_all(bind=bind, tables=missing, checkfirst=False)
if not settings.shares_identity:
op.execute(event_policies_sql())
op.execute(_grants())
def downgrade() -> None:
if get_settings().shares_identity:
raise RuntimeError("signing: no downgrade on the platform.")
bind = op.get_bind()
own = _own(bind)
for table in reversed((EVENT_LOG, *OWN_TABLES)):
if _exists(bind, own, table):
op.execute(f"DROP TABLE {_q(own)}.{_q(table)} CASCADE")
+5 -21
View File
@@ -94,15 +94,14 @@ class Settings(BaseSettings):
_require_verified_tls(name, getattr(self, name.lower()), self.db_local_hosts)
return self
# Working directory for anything written to disk. A request's uploaded PDF and every signed
# result live under DATA_DIR/files (dredd_core.plain_files), one file = one id, never overwritten.
# Working directory for anything written to disk. Uploaded files live under DATA_DIR/files
# (dredd_core.plain_files), one file = one id, never overwritten.
data_dir: str = "data"
# ── Galena (D9) ───────────────────────────────────────────────────────────────
# Galena's PUBLIC base URL (`https://<site>/galena`). A request on a Galena document reads it and
# writes the signed PDF back as a new version of it, through Galena's API with the acting
# person's token (dredd_core.module_client). Empty = Galena is off for this module: requests are
# plain files only, and one already on a document answers 409 `galena_disabled`.
# Galena's PUBLIC base URL (`https://<site>/galena`), called through Galena's API with the
# acting person's token (dredd_core.module_client). Empty = Galena is off for this module and
# one already on a document answers 409 `galena_disabled`.
galena_base_url: str = ""
@field_validator("galena_base_url")
@@ -114,21 +113,6 @@ class Settings(BaseSettings):
check_base_url(v)
return v
# ── The signer (PAdES, pyHanko) ───────────────────────────────────────────────
# The operator's signing certificate and key, as ONE PKCS#12 file mounted into the container
# (never in the repo, never in the image). Its passphrase comes from SIGNING_PKCS12_PASSPHRASE or,
# preferably, from a secret file (SIGNING_PKCS12_PASSPHRASE_FILE, e.g. /run/secrets/...). Empty
# path = signing is not configured: requests can be created and verified, and "Podpisz" answers
# 409 `signing_unconfigured`.
signing_pkcs12_path: str = ""
signing_pkcs12_passphrase: str = ""
signing_pkcs12_passphrase_file: str = ""
# PEM file of CA certificates a signature is VALIDATED against (verification's "zaufany").
# Empty = no trust anchors: a signature can still be reported intact and cryptographically valid.
signing_trust_roots: str = ""
# What the signature dictionary says (/Location); the reason is the request's own.
signing_location: str = ""
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — the default, and what this repo's own compose stack runs —
# is the STANDALONE deployment: Parafa owns `app_user` / `session` / `module_permission` in
+1 -1
View File
@@ -21,7 +21,7 @@ from dredd_core.enums import SessionKind, TokenScope
# ── Parafa's own ────────────────────────────────────────────────────────
# None yet: Parafa keeps its states as text with a CHECK (`models/signing.py`).
# None yet.
__all__ = [
+3 -3
View File
@@ -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, health, users
API_PREFIX = "/api/v1"
@@ -83,7 +83,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
app = FastAPI(
title="Parafa API",
version=__version__,
description="Podpisy PAdES: wnioski o podpis, podpisane pliki, weryfikacja podpisu.",
description="Obiegi akceptacji dokumentów i wniosków.",
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
@@ -118,7 +118,7 @@ if settings.cors_origins_list:
for router in (
health.router, auth.router, users.router, admin.router,
signing.router, dashboard.router,
dashboard.router,
):
app.include_router(router, prefix=API_PREFIX)
+5 -8
View File
@@ -22,9 +22,9 @@ are still created by the migration. They stay empty and unused; that is expected
Leave them alone rather than trying to drop them — a later move to tree tenancy just starts
using them.
Parafa's own model is in `.signing`. Module events come from dredd-core (`dredd_core.events`,
v0.20.0): Parafa SENDS `document.signed`. Standalone the log `module_event` is this app's own; on the
platform it is the hub's, which is why `SHARED_TABLES` holds it beside the identity tables.
Module events come from dredd-core (`dredd_core.events`, v0.20.0). Standalone the log
`module_event` is this app's own; on the platform it is the hub's, which is why `SHARED_TABLES`
holds it beside the identity tables.
"""
from dredd_core import (
AppSetting,
@@ -41,8 +41,6 @@ from dredd_core import (
from dredd_core.events import EventCursor, EventReceipt, ModuleEvent
from dredd_core.identity import EVENT_TABLES, SHARED_IDENTITY_TABLES
from .signing import SigningRequest
#: The tables that belong to the platform, not to this app, when it is a module of it: the shared
#: 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
@@ -60,8 +58,7 @@ SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | EVENT_TABLES
#: The runtime role may INSERT and SELECT, never UPDATE, DELETE or TRUNCATE.
APPEND_ONLY_TABLES: tuple[str, ...] = ("audit_log", "module_event", "module_event_receipt")
#: The runtime role may never DELETE or TRUNCATE (a decision that must survive; supersede it instead).
#: A signing request is evidence of what was signed, by whom and when: never removed.
NO_DELETE_TABLES: tuple[str, ...] = ("signing_request",)
NO_DELETE_TABLES: tuple[str, ...] = ()
__all__ = [
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
@@ -70,6 +67,6 @@ __all__ = [
# but the table is on `Base.metadata`, so it has to be re-exported here or `own_tables(...,
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
"SigningRequest", "ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
"ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
]
-80
View File
@@ -1,80 +0,0 @@
"""The signing request (wniosek o podpis): Parafa's subject of work (the Compass split plan,
work package M6).
**`signing_request`** is one row pinned to exactly one Galena document or one plain file, in the two
`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
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`).
A request is evidence of what was signed, by whom and when, so it is `NO_DELETE`
(`models/__init__.py`): a request nobody wants any more stays as it is.
"""
from __future__ import annotations
import datetime as dt
import uuid
from dredd_core import Base, TimestampMixin, UUIDPkMixin
from dredd_core.document_ref import MAX_NAME, SubjectRefMixin
from sqlalchemy import (
BigInteger,
CheckConstraint,
DateTime,
ForeignKey,
Index,
String,
Text,
Uuid,
text,
)
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")
def _one_of(column: str, values: tuple[str, ...]) -> str:
return f"{column} IN ({', '.join(repr(v) for v in values)})"
class SigningRequest(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
__tablename__ = "signing_request"
title: Mapped[str] = mapped_column(Text, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
#: Goes into the signature dictionary's /Reason.
reason: Mapped[str | None] = mapped_column(Text)
status: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'draft'"))
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
# ── the signed result ────────────────────────────────────────────────────
signed_file_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
signed_sha256: Mapped[str | None] = mapped_column(String(64))
signed_size: Mapped[int | None] = mapped_column(BigInteger)
signed_name: Mapped[str | None] = mapped_column(String(MAX_NAME))
signed_commit_sha: Mapped[str | None] = mapped_column(String(64))
signed_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
signed_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
#: The signer certificate's subject at the time, so the list needs no certificate to show it.
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)
__table_args__ = (
*SubjectRefMixin.subject_ref_constraints(),
CheckConstraint(_one_of("status", STATUSES), name="status"),
CheckConstraint(
"status <> 'signed' OR (signed_file_id IS NOT NULL AND signed_sha256 IS NOT NULL "
"AND signed_size IS NOT NULL AND signed_name IS NOT NULL AND signed_at IS NOT NULL)",
name="signed_has_result"),
CheckConstraint("signed_sha256 IS NULL OR signed_sha256 ~ '^[0-9a-f]{64}$'",
name="signed_sha256"),
Index("ix_signing_request_status", "status"),
Index("ix_signing_request_owner", "owner_id"),
Index("ix_signing_request_document", "ref_document_id"),
)
+13 -16
View File
@@ -1,28 +1,25 @@
"""What the console's landing screen needs, in one round trip, and `GET /stats` (dredd-core's stats
contract, read by Panorama with the person's own session). Both count through the same
permission-filtered service the lists use, so a tile can never report a request its reader may not
open, and each stats tile equals the list its link opens.
"""`GET /stats`: dredd-core's stats contract, read by Panorama with the person's own session.
Each tile must equal the list its link opens. Those lists do not exist yet, so both tiles are 0
until the runs services count them with the very filter their lists apply.
"""
from __future__ import annotations
from dredd_core import stats_contract
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..config import get_settings
from ..deps import get_current_user
from ..models import AppUser
from ..services import signing as service
router = APIRouter(tags=["dashboard"])
@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.dashboard(db, user)
@router.get("/stats")
def module_stats(db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.module_stats(db, user)
def module_stats(_user: AppUser = Depends(get_current_user)) -> dict:
# ponytail: placeholder counts; the real ones come with the inbox and mine lists.
tiles = [
stats_contract.make_tile(key="inbox", label="Czeka na mnie", count=0, link="inbox"),
stats_contract.make_tile(key="running", label="W toku", count=0, link="mine"),
]
return stats_contract.make_response(get_settings().module_slug, tiles)
-112
View File
@@ -1,112 +0,0 @@
"""Signing requests over HTTP: the two lists, a request from an upload or a Galena document, the
bytes, signing, and signature verification. No SQL and no access rule here: `services/signing.py`
owns both (a request somebody may not see is a 404). `sign` commits itself, as an upload does,
because it moves bytes; the rest commit here.
"""
from __future__ import annotations
import uuid
from typing import Literal
from dredd_core.plain_files import MAX_FILE_BYTES
from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile
from fastapi.responses import 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 ..schemas import RequestDocumentIn
from ..services import signing as service
router = APIRouter(tags=["signing"])
async def _read_upload(file: UploadFile) -> bytes:
data = await file.read(MAX_FILE_BYTES + 1)
if len(data) > MAX_FILE_BYTES:
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
return data
@router.get("/requests")
def list_requests(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
view: Literal["todo", "signed"] | None = Query(None),
q: str = Query("", max_length=200)) -> list[dict]:
return service.list_requests(db, user, view=view, q=q)
@router.post("/requests/upload", status_code=201)
async def create_from_file(request: Request, file: UploadFile = File(...),
title: str | None = Form(None, max_length=200),
note: str | None = Form(None, max_length=4000),
reason: str | None = Form(None, max_length=200),
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
data = await _read_upload(file)
out = service.create_from_file(db, user, data=data, name=file.filename or "plik.pdf",
title=title, note=note, reason=reason, ip=client_ip(request))
db.commit()
return out
@router.post("/requests/document", status_code=201)
def create_from_document(body: RequestDocumentIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = service.create_from_document(
db, user, document_id=body.document_id, path=body.path, version=body.version,
token=extract_token(request), title=body.title, note=body.note, reason=body.reason,
ip=client_ip(request))
db.commit()
return out
@router.get("/requests/{request_id}")
def get_request(request_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.as_dict(db, service.for_reading(db, user, request_id), user)
@router.post("/requests/{request_id}/sign")
def sign(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.sign(db, actor=user, request_id=request_id, token=extract_token(request),
ip=client_ip(request))
@router.get("/requests/{request_id}/original")
def original(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> Response:
data, media, headers = service.original(db, user, request_id, token=extract_token(request),
ip=client_ip(request))
db.commit()
return Response(content=data, media_type=media, headers=headers)
@router.get("/requests/{request_id}/signed")
def signed(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> Response:
data, media, headers = service.signed_file(db, user, request_id, ip=client_ip(request))
db.commit()
return Response(content=data, media_type=media, headers=headers)
@router.get("/requests/{request_id}/verify")
def verify_request(request_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.verify_request(db, user, request_id)
@router.post("/verify")
async def verify_upload(request: Request, file: UploadFile = File(...),
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
data = await _read_upload(file)
# pyHanko's validation runs its own event loop (asyncio.run), which cannot start inside this
# one: the work goes to the thread pool, as a sync route's would.
out = await run_in_threadpool(service.verify_upload, db, user, data=data,
name=file.filename or "plik.pdf", ip=client_ip(request))
db.commit()
return out
-11
View File
@@ -103,17 +103,6 @@ class GrantIn(BaseModel):
role: NodeRole
# ── signing requests ──────────────────────────────────────────────────────────
class RequestDocumentIn(BaseModel):
"""A request on a Galena document: the project id, the file's path, the version to pin."""
document_id: uuid.UUID
path: str = Field(min_length=1, max_length=1024)
version: str = Field(default="main", min_length=1, max_length=200)
title: str | None = Field(default=None, max_length=200)
note: str | None = Field(default=None, max_length=4000)
reason: str | None = Field(default=None, max_length=200)
# ── administration ────────────────────────────────────────────────────────────
class SettingsIn(BaseModel):
"""A partial set of settings to change, validated against `services/settings.SPECS`."""
-233
View File
@@ -1,233 +0,0 @@
"""PAdES signing and signature validation with pyHanko (MIT). No database, no HTTP: bytes in, bytes or
a report out, so it is tested on its own with a throwaway certificate made at test time.
**The signer is the operator's**, one PKCS#12 file named by `SIGNING_PKCS12_PATH`, its passphrase
from `SIGNING_PKCS12_PASSPHRASE_FILE` (a secret file, preferred) or `SIGNING_PKCS12_PASSPHRASE`. No
key ever lives in the repo or the image. The loaded signer is cached per (path, mtime) so a renewed
certificate is picked up without a restart.
**What a signature is here:** PAdES baseline B-B (`/SubFilter /ETSI.CAdES.detached`, SHA-256), added
as an incremental update, so every earlier signature in the file stays intact. No timestamp
authority and no revocation fetching: both are network calls to third parties, an operator choice
for later (B-T / B-LT), never a default.
**What a verification reports**, per embedded signature: `intact` (the signed bytes are unchanged),
`valid` (the cryptography checks out), `trusted` (the signer's chain reaches one of
`SIGNING_TRUST_ROOTS`; with none configured it is always false), whether it covers the whole file or
later revisions were added, the signer's subject and the claimed signing time. Revocation is not
checked (no fetching), which the report says.
"""
from __future__ import annotations
import datetime as dt
import io
import os
import threading
from pathlib import Path
from ..config import get_settings
from ..errors import ConflictError, ValidationError
#: What a request's subject may be. Everything else is refused before any bytes are stored.
PDF_EXTENSION = ".pdf"
PDF_MEDIA = "application/pdf"
MAX_REASON = 200
def is_pdf_name(name: str) -> bool:
return (name or "").strip().lower().endswith(PDF_EXTENSION)
def check_pdf(name: str, data: bytes) -> None:
"""A PDF by name AND by its first bytes, or a Polish 422 that says so."""
if not is_pdf_name(name):
raise ValidationError("Parafa podpisuje tylko pliki PDF. Zapisz dokument jako PDF i spróbuj "
"ponownie.", {"code": "pdf_only"})
if not data:
raise ValidationError("Plik jest pusty.", {"code": "file_empty"})
if not data.lstrip()[:5] == b"%PDF-":
raise ValidationError("To nie jest plik PDF.", {"code": "format_mismatch"})
def signed_name(name: str) -> str:
"""`umowa.pdf` -> `umowa.podpisany.pdf`."""
stem = name[: -len(PDF_EXTENSION)] if is_pdf_name(name) else name
return f"{stem}.podpisany{PDF_EXTENSION}"
# ── the signer ────────────────────────────────────────────────────────────────
_lock = threading.Lock()
_cache: dict[tuple[str, float], object] = {}
def _passphrase() -> bytes | None:
s = get_settings()
if s.signing_pkcs12_passphrase_file:
try:
value = Path(s.signing_pkcs12_passphrase_file).read_text(encoding="utf-8").rstrip("\r\n")
except OSError as exc:
raise ConflictError("Nie można odczytać pliku z hasłem certyfikatu.",
{"code": "signing_passphrase_unreadable"}) from exc
return value.encode("utf-8")
if s.signing_pkcs12_passphrase:
return s.signing_pkcs12_passphrase.encode("utf-8")
return None
def configured() -> bool:
return bool(get_settings().signing_pkcs12_path)
def signer():
"""The operator's pyHanko signer, or a 409 saying signing is not set up."""
from pyhanko.sign import signers
path = get_settings().signing_pkcs12_path
if not path:
raise ConflictError("Podpisywanie nie jest skonfigurowane (brak certyfikatu operatora).",
{"code": "signing_unconfigured"})
try:
mtime = os.stat(path).st_mtime
except OSError as exc:
raise ConflictError("Plik certyfikatu operatora jest niedostępny.",
{"code": "signing_certificate_missing"}) from exc
with _lock:
hit = _cache.get((path, mtime))
if hit is not None:
return hit
loaded = signers.SimpleSigner.load_pkcs12(path, passphrase=_passphrase())
if loaded is None:
raise ConflictError("Nie można wczytać certyfikatu operatora (złe hasło albo plik).",
{"code": "signing_certificate_invalid"})
_cache.clear()
_cache[(path, mtime)] = loaded
return loaded
def signer_subject() -> str | None:
if not configured():
return None
try:
return signer().signing_cert.subject.human_friendly
except ConflictError:
return None
# ── signing ───────────────────────────────────────────────────────────────────
def sign(data: bytes, *, reason: str | None = None, field_name: str | None = None,
signer_obj=None) -> bytes:
"""`data` with one more PAdES signature, as an incremental update. Raises ValidationError when
the bytes are not a PDF pyHanko can read (encrypted, broken)."""
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.pdf_utils.misc import PdfError
from pyhanko.sign import fields, signers
signer_obj = signer_obj or signer()
try:
writer = IncrementalPdfFileWriter(io.BytesIO(data), strict=False)
except (PdfError, ValueError, KeyError) as exc:
raise ValidationError("Nie można odczytać tego pliku PDF.", {"code": "pdf_unreadable"}) from exc
if writer.prev.encrypted:
raise ValidationError("Zaszyfrowanego pliku PDF nie da się podpisać.",
{"code": "pdf_encrypted"})
taken = {name for name, _, _ in fields.enumerate_sig_fields(writer.prev)}
if field_name is None:
n = 1
while f"Parafa{n}" in taken:
n += 1
field_name = f"Parafa{n}"
meta = signers.PdfSignatureMetadata(
field_name=field_name, md_algorithm="sha256",
subfilter=fields.SigSeedSubFilter.PADES,
reason=(reason or None), location=(get_settings().signing_location or None))
try:
out = signers.sign_pdf(writer, meta, signer=signer_obj)
except PdfError as exc:
raise ValidationError(f"Nie można podpisać tego pliku PDF: {exc}"[:500],
{"code": "pdf_unsignable"}) from exc
return out.getvalue()
# ── verification ──────────────────────────────────────────────────────────────
def _trust_roots() -> list:
from asn1crypto import pem, x509
path = get_settings().signing_trust_roots
if not path:
return []
try:
raw = Path(path).read_bytes()
except OSError as exc:
raise ConflictError("Plik zaufanych certyfikatów jest niedostępny.",
{"code": "trust_roots_missing"}) from exc
certs = []
if pem.detect(raw):
for _, _, der in pem.unarmor(raw, multiple=True):
certs.append(x509.Certificate.load(der))
else:
certs.append(x509.Certificate.load(raw))
return certs
def _iso(value) -> str | None:
if value is None:
return None
if isinstance(value, dt.datetime):
return value.isoformat()
return str(value)
def verify(data: bytes, *, extra_roots: list | None = None) -> dict:
"""Every embedded signature of `data`, validated. Raises ValidationError on a non-PDF."""
from pyhanko.pdf_utils.misc import PdfError
from pyhanko.pdf_utils.reader import PdfFileReader
from pyhanko.sign.validation import validate_pdf_signature
from pyhanko_certvalidator import ValidationContext
if not data.lstrip()[:5] == b"%PDF-":
raise ValidationError("To nie jest plik PDF.", {"code": "format_mismatch"})
try:
reader = PdfFileReader(io.BytesIO(data), strict=False)
embedded = list(reader.embedded_signatures)
except (PdfError, ValueError, KeyError) as exc:
raise ValidationError("Nie można odczytać tego pliku PDF.", {"code": "pdf_unreadable"}) from exc
roots = [*_trust_roots(), *(extra_roots or [])]
out = []
for sig in embedded:
context = ValidationContext(trust_roots=roots, allow_fetching=False)
entry: dict = {"field": sig.field_name}
try:
status = validate_pdf_signature(sig, context)
cert = status.signing_cert
entry |= {
"intact": bool(status.intact),
"valid": bool(status.valid),
"trusted": bool(status.trusted),
"coverage": getattr(status.coverage, "name", str(status.coverage)),
"modification": getattr(status.modification_level, "name", None),
"signer": cert.subject.human_friendly if cert is not None else None,
"issuer": cert.issuer.human_friendly if cert is not None else None,
"signed_at": _iso(status.signer_reported_dt),
"md_algorithm": status.md_algorithm,
"pades": (sig.sig_object.get("/SubFilter") == "/ETSI.CAdES.detached"),
"summary": status.summary(),
"error": None,
}
except Exception as exc: # noqa: BLE001 - one bad signature must not hide the others
entry |= {"intact": False, "valid": False, "trusted": False, "coverage": None,
"modification": None, "signer": None, "issuer": None, "signed_at": None, "md_algorithm": None,
"pades": None, "summary": None,
"error": f"{exc.__class__.__name__}: {exc}"[:500]}
out.append(entry)
return {
"signatures": out,
"count": len(out),
"all_valid": bool(out) and all(e["intact"] and e["valid"] for e in out),
"trust_configured": bool(roots),
"revocation_checked": False,
}
-367
View File
@@ -1,367 +0,0 @@
"""Signing requests (wnioski o podpis): Parafa's subject of work, the lists, signing, verification
(the Compass split plan, work package M6).
**The subject** is one row in one of the two `dredd_core.document_ref` shapes, no foreign key across
modules: a Galena document pinned at the commit it was asked for (with Galena), or one uploaded file
in `plain_files` (always). PDF only; anything else is a 422 that says so before any byte is stored.
**Who may do what** (simple tenancy, `services/authz.py`): anybody admitted to this module may ask
for a signature and sees their own requests; this module's moderators see every request and are the
only ones who may SIGN, because the certificate is the operator's (the institution's seal), not the
person's. A request somebody may not see is a 404, never a 403. With Galena, Galena still decides
whether the person may read the document or write its new version: every call there carries the
person's own token.
**Signing** (`sign`) reads the subject's bytes (verified against the pinned hash), adds one PAdES
signature (`services/pades.py`), stores the signed bytes as a NEW `plain_files` file and — for a
Galena subject — writes them back to Galena as a new version of the same document (`POST
/projects/{id}/upload` with `dest` = its path), pinning the commit Galena answers and reading it
back once to prove the hash. In the same transaction it records the audit entry and emits
`document.signed` (dredd-core `events`; identifiers only). A failure that is the document's (an
encrypted PDF, Galena refusing the write) leaves the request `failed` with the reason, and a retry is
allowed; a failure that is the operator's (no certificate configured) changes nothing.
"""
from __future__ import annotations
import datetime as dt
import uuid
from functools import lru_cache
from dredd_core import document_ref, stats_contract
from dredd_core import events as core_events
from dredd_core.document_ref import DocumentRef, FileRef
from dredd_core.errors import AppError
from dredd_core.module_client import ModuleClient, multipart
from dredd_core.plain_files import PlainFiles, response_headers
from sqlalchemy import func, select
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
MAX_TITLE = 200
MAX_NOTE = 4000
#: 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",)}
@lru_cache
def files() -> PlainFiles:
return PlainFiles(get_settings().data_dir)
def galena() -> ModuleClient | None:
base = get_settings().galena_base_url
return ModuleClient(base, service="Galena") if base else None
def galena_or_refuse() -> ModuleClient:
client = galena()
if client is None:
raise ConflictError("Galena nie jest włączona dla tego modułu.",
{"code": "galena_disabled"})
return client
def ref_name(ref) -> str:
return ref.name if isinstance(ref, FileRef) else ref.path.rsplit("/", 1)[-1]
def _iso(value) -> str | None:
return value.isoformat() if value is not None else None
def _name_of(db: DbSession, user_id: uuid.UUID | None) -> str | None:
if user_id is None:
return None
person = db.get(AppUser, user_id)
return (person.full_name or person.email) if person is not None else None
def signed_ref(row: SigningRequest) -> FileRef | None:
if row.signed_file_id is None:
return None
return FileRef(file_id=row.signed_file_id, sha256=row.signed_sha256, size=row.signed_size,
name=row.signed_name)
def as_dict(db: DbSession, row: SigningRequest, user: AppUser) -> dict:
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),
"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 {
"name": row.signed_name, "sha256": row.signed_sha256, "size": row.signed_size,
"commit_sha": row.signed_commit_sha, "at": _iso(row.signed_at),
"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),
}
# ── access ────────────────────────────────────────────────────────────────────
def for_reading(db: DbSession, user: AppUser, request_id: uuid.UUID) -> SigningRequest:
row = db.get(SigningRequest, request_id)
if row is None or not authz.can_read(db, user, row.owner_id):
raise NotFoundError("Not found.")
return row
def _visible(db: DbSession, user: AppUser):
stmt = select(SigningRequest)
if not moderation.is_moderator(db, user):
stmt = stmt.where(SigningRequest.owner_id == user.id)
return stmt
# ── lists, dashboard, stats ───────────────────────────────────────────────────
def list_requests(db: DbSession, user: AppUser, *, view: str | None = None, q: str = "") -> list[dict]:
"""A list the person may see: `todo` (Do podpisu: draft + failed), `signed` (Podpisane), or all."""
stmt = _visible(db, user)
if view is not None:
if view not in VIEWS:
raise ValidationError("Nieznana lista.", {"code": "view_unknown"})
stmt = stmt.where(SigningRequest.status.in_(VIEWS[view]))
if q:
stmt = stmt.where(SigningRequest.title.ilike(f"%{q}%"))
rows = db.scalars(stmt.order_by(SigningRequest.updated_at.desc(), SigningRequest.id)).all()
return [as_dict(db, r, user) for r in rows]
def count(db: DbSession, user: AppUser, view: str) -> int:
"""The length of `list_requests(view=view)` for this person: the same filter, counted."""
stmt = _visible(db, user).where(SigningRequest.status.in_(VIEWS[view]))
return db.scalar(select(func.count()).select_from(stmt.subquery())) or 0
def dashboard(db: DbSession, user: AppUser) -> dict:
todo = list_requests(db, user, view="todo")
return {"cards": {"todo": len(todo), "signed": count(db, user, "signed")},
"recent": todo[:8], "signing_configured": pades.configured(),
"signer": pades.signer_subject(), "galena": galena() is not None}
def module_stats(db: DbSession, user: AppUser) -> 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`)."""
tiles = [
stats_contract.make_tile(key="to_sign", label="Do podpisu", count=count(db, user, "todo"),
link="todo"),
stats_contract.make_tile(key="signed", label="Podpisane", count=count(db, user, "signed"),
link="signed"),
]
return stats_contract.make_response(get_settings().module_slug, tiles)
# ── creating a request ────────────────────────────────────────────────────────
def _text(value: str | None, limit: int, what: str) -> str | None:
value = (value or "").strip() or None
if value and len(value) > limit:
raise ValidationError(f"{what} ma najwyżej {limit} znaków.")
return value
def _new(db: DbSession, user: AppUser, ref, *, title: str | None, note: str | None,
reason: str | None, ip: str | None) -> dict:
row = SigningRequest(title=_text(title, MAX_TITLE, "Tytuł") or ref_name(ref),
note=_text(note, MAX_NOTE, "Notatka"),
reason=_text(reason, pades.MAX_REASON, "Powód podpisu"),
status="draft", owner_id=user.id, created_by=user.id)
row.set_ref(ref)
db.add(row)
db.flush()
audit.record(db, action="signing.requested", entity_type="signing_request", entity_id=row.id,
actor_id=user.id, detail=ref_name(ref), ip=ip)
return as_dict(db, row, user)
def create_from_file(db: DbSession, user: AppUser, *, data: bytes, name: str,
title: str | None = None, note: str | None = None, reason: str | None = None,
ip: str | None = None) -> dict:
"""A request without Galena: the PDF goes to plain_files, one file = one id. No commit; the file
is removed again if the row cannot be written."""
pades.check_pdf(name, data)
ref = files().save(data, name)
try:
return _new(db, user, ref, title=title, note=note, reason=reason, ip=ip)
except Exception:
files().delete(ref.file_id)
raise
def create_from_document(db: DbSession, user: AppUser, *, document_id: uuid.UUID, path: str,
version: str = "main", token: str | None, title: str | None = None,
note: str | None = None, reason: str | None = None,
ip: str | None = None) -> dict:
"""A request on a Galena document, pinned at its current commit on `version`, read as the
person. No commit."""
if not pades.is_pdf_name(path):
raise ValidationError("Parafa podpisuje tylko pliki PDF. Wybierz dokument PDF.",
{"code": "pdf_only"})
client = galena_or_refuse()
ref = document_ref.pin_document(client, document_id, path, token=token, ref=version)
data = document_ref.read_document(client, ref, token=token)
pades.check_pdf(path, data)
return _new(db, user, ref, title=title, note=note, reason=reason, ip=ip)
# ── bytes ─────────────────────────────────────────────────────────────────────
def _download(db: DbSession, user: AppUser, row: SigningRequest, data: bytes, name: str,
what: str, ip: str | None) -> tuple[bytes, str, dict]:
audit.record(db, action=f"signing.{what}_downloaded", entity_type="signing_request",
entity_id=row.id, actor_id=user.id, detail=name, ip=ip)
media, headers = response_headers(name, download=True)
return data, media, headers
def original(db: DbSession, user: AppUser, request_id: uuid.UUID, *, token: str | None,
ip: str | None = None) -> tuple[bytes, str, dict]:
"""The subject's bytes as they were pinned. Always a download (core's rule for untrusted bytes:
nothing a person uploaded is rendered in this origin). No commit."""
row = for_reading(db, user, request_id)
data = document_ref.read(row.ref, files=files(), galena=galena(), token=token)
return _download(db, user, row, data, ref_name(row.ref), "original", ip)
def signed_file(db: DbSession, user: AppUser, request_id: uuid.UUID, *,
ip: str | None = None) -> tuple[bytes, str, dict]:
row = for_reading(db, user, request_id)
ref = signed_ref(row)
if ref is None:
raise NotFoundError("Ten wniosek nie ma jeszcze podpisanego pliku.")
return _download(db, user, row, files().read(ref), ref.name, "signed", ip)
# ── signing ───────────────────────────────────────────────────────────────────
def _write_back_to_galena(ref: DocumentRef, data: bytes, *, token: str | None) -> str:
"""The signed PDF as a new version of the subject's Galena document, as the acting person.
Returns the commit Galena answered, after reading it back to prove the bytes."""
client = galena_or_refuse()
body, ctype = multipart({"dest": ref.path},
{"file": (ref_name(ref), data, pades.PDF_MEDIA)})
response = client.request("POST", f"/projects/{ref.document_id}/upload", token=token,
body=body, content_type=ctype)
response.raise_for_status(client.service, "Galena nie zapisała podpisanego pliku.")
commit = (response.json() or {}).get("sha")
if not isinstance(commit, str) or not commit:
raise ConflictError("Galena nie podała zapisanej wersji.", {"code": "galena_no_commit"})
pinned = DocumentRef(document_id=ref.document_id, path=ref.path, commit_sha=commit,
sha256=document_ref.sha256_of(data))
document_ref.read_document(client, pinned, token=token)
return commit
def event_payload(row: SigningRequest) -> dict:
"""Identifiers only (events.check_payload): never a title, a name or a reason."""
payload: dict = {"request_id": row.id, "sha256": row.signed_sha256,
"file_id": row.signed_file_id}
ref = row.ref
if isinstance(ref, DocumentRef):
payload |= {"document_id": ref.document_id, "commit_sha": row.signed_commit_sha,
"signed_from": ref.commit_sha}
return payload
def _fail(db: DbSession, row: SigningRequest, actor: AppUser, message: str, ip: str | None) -> None:
row.status = "failed"
row.error = message[:1000]
audit.record(db, action="signing.failed", entity_type="signing_request", entity_id=row.id,
actor_id=actor.id, detail=message[:500], ip=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)
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"})
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)
except Exception as exc: # noqa: BLE001 - every failure is recorded on the request, then raised
db.rollback()
if saved is not None:
files().delete(saved.file_id)
message = (exc.detail if isinstance(exc, AppError)
else f"Podpis nie powiódł się ({exc.__class__.__name__}: {exc})")
_fail(db, db.get(SigningRequest, request_id), actor, message, ip)
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
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()
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.
raise
return as_dict(db, row, actor)
# ── verification ──────────────────────────────────────────────────────────────
def verify_upload(db: DbSession, user: AppUser, *, data: bytes, name: str,
ip: str | None = None) -> dict:
"""Validate the signatures of a PDF the person uploads. Nothing is stored. No commit."""
pades.check_pdf(name, data)
report = pades.verify(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}
def verify_request(db: DbSession, user: AppUser, request_id: uuid.UUID) -> dict:
"""Validate the signed result of a request."""
row = for_reading(db, user, request_id)
ref = signed_ref(row)
if ref is None:
raise NotFoundError("Ten wniosek nie ma jeszcze podpisanego pliku.")
return {"name": ref.name, "sha256": ref.sha256, **pades.verify(files().read(ref))}
-5
View File
@@ -47,11 +47,6 @@ argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depe
# this is now a re-pin rather than the only source — kept explicit so
# the version is visible here and the license gate sees it named.
# PAdES signing and signature validation (the signing module's whole domain)
pyhanko==0.38.1 # MIT; pulls pyhanko-certvalidator (MIT), asn1crypto (MIT),
# cryptography (Apache-2.0/BSD), requests (Apache-2.0), tzlocal (MIT),
# pyyaml (MIT), qrcode (BSD) - the license gate checks the whole closure
# Outbound HTTP — the ONE client, used only from app/integrations/.
httpx==0.28.1 # BSD-3-Clause
-67
View File
@@ -1,67 +0,0 @@
"""Test-time PKI and PDFs: a throwaway self-signed signer made on the fly, never committed.
`make_signer(tmp_path)` writes a PKCS#12 (key + certificate) into pytest's temp directory and
returns (path, passphrase, certificate PEM path); `minimal_pdf()` returns a one-page PDF built by
hand, with a correct cross-reference table, so no PDF library is needed to make test input.
"""
from __future__ import annotations
import datetime as dt
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography.x509.oid import NameOID
PASSPHRASE = "test-only-passphrase"
def make_signer(directory: Path, *, cn: str = "Parafa Test Signer") -> tuple[Path, str, Path]:
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Parafa tests")])
now = dt.datetime.now(dt.UTC)
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - dt.timedelta(days=1)).not_valid_after(now + dt.timedelta(days=30))
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=True,
key_encipherment=False, data_encipherment=False,
key_agreement=False, key_cert_sign=True, crl_sign=True,
encipher_only=False, decipher_only=False), critical=True)
.sign(key, hashes.SHA256()))
p12 = pkcs12.serialize_key_and_certificates(
b"signer", key, cert, None,
serialization.BestAvailableEncryption(PASSPHRASE.encode()))
directory.mkdir(parents=True, exist_ok=True)
path = directory / "signer.p12"
path.write_bytes(p12)
pem = directory / "signer.pem"
pem.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
return path, PASSPHRASE, pem
def minimal_pdf(text: str = "Umowa testowa") -> bytes:
stream = f"BT /F1 18 Tf 72 720 Td ({text}) Tj ET".encode("latin-1")
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R "
b"/Resources << /Font << /F1 5 0 R >> >> >>",
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
out = bytearray(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n")
offsets = []
for i, body in enumerate(objects, start=1):
offsets.append(len(out))
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
xref = len(out)
out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
for off in offsets:
out += f"{off:010d} 00000 n \n".encode()
out += (f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
.encode())
return bytes(out)
-2
View File
@@ -353,8 +353,6 @@ def test_every_column_that_names_a_person_is_found():
found = {(table, column) for table, column, _ in rev._person_columns()}
assert ("audit_log", "actor_id") in found
assert ("app_setting", "updated_by") in found
assert ("signing_request", "owner_id") in found # the app's own subject table
assert ("signing_request", "signed_by") in found
# The shared tables' own person-columns are the hub's, in the hub's schema, and were never local.
assert not any(table in {"app_user", "session", "module_permission"} for table, _ in found)
+3 -183
View File
@@ -5,19 +5,16 @@ setting a test changes is put back, so the suite can be re-run against the same
cannot be deleted, only deactivated, and nothing here depends on a clean slate.
This is the floor every app in the family inherits: authentication, the admin boundary, the closed
settings set, access control on signing requests, bad input as 422 (never 500), the cross-site write
settings set, bad input as 422 (never 500), the cross-site write
refusal, and the append-only audit log held by the database itself.
"""
from __future__ import annotations
import importlib.util
import json as _json
import uuid
import pytest
from conftest import ADMIN_EMAIL, ADMIN_PASSWORD, USER_PASSWORD, bearer, integration, settings_set
from dredd_core import stats_contract
from pki import make_signer, minimal_pdf
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
@@ -36,14 +33,6 @@ def root_id(admin_client):
return next(u["id"] for u in units if u["parent_id"] is None)
def _upload(client, headers, name: str = "umowa.pdf", data: bytes | None = None, **form) -> dict:
payload = data if data is not None else minimal_pdf()
r = client.post("/api/v1/requests/upload", headers=headers, data=form,
files={"file": (name, payload, "application/pdf")})
assert r.status_code == 201, r.text
return r.json()
# ── authentication ────────────────────────────────────────────────────────────
def test_health_is_public(client):
assert client.get("/api/v1/health").json()["status"] == "ok"
@@ -67,7 +56,6 @@ def test_anonymous_requests_are_refused():
anon = TestClient(app)
assert anon.get("/api/v1/auth/me").status_code == 401
assert anon.get("/api/v1/requests").status_code == 401
assert anon.get("/api/v1/stats").status_code == 401
@@ -103,177 +91,9 @@ def test_settings_are_a_closed_typed_set(admin_client):
assert admin_client.get("/api/v1/config").json()["settings"]["instance_name"] != name
# ── signing requests ──────────────────────────────────────────────────────────
@pytest.fixture
def signer(tmp_path, monkeypatch):
"""A throwaway operator certificate made now (tests/pki.py), never committed."""
from app import config
p12, passphrase, pem = make_signer(tmp_path / "pki")
monkeypatch.setattr(config.get_settings(), "signing_pkcs12_path", str(p12))
monkeypatch.setattr(config.get_settings(), "signing_pkcs12_passphrase", passphrase)
monkeypatch.setattr(config.get_settings(), "signing_trust_roots", str(pem))
return pem
def _event(request_id: str):
from app.db import engine
with engine.connect() as conn:
return conn.execute(text("SELECT kind, source_module, payload FROM module_event "
"WHERE payload->>'request_id' = :r"), {"r": request_id}).all()
def test_requests_are_private_and_only_pdfs(admin_client, make_user):
owner, stranger = make_user("owner"), make_user("stranger")
h_owner, h_other = bearer(owner["token"]), bearer(stranger["token"])
req = _upload(admin_client, h_owner, title=f"Umowa {RUN}", reason="Akceptacja")
assert req["status"] == "draft" and req["ref"]["kind"] == "file" and req["can_sign"] is False
assert admin_client.get(f"/api/v1/requests/{req['id']}", headers=h_other).status_code == 404
seen = {x["id"] for x in admin_client.get("/api/v1/requests", headers=h_other).json()}
assert req["id"] not in seen
assert admin_client.get(f"/api/v1/requests/{req['id']}/original",
headers=h_other).status_code == 404
# The original comes back as a download, never rendered in this origin.
r = admin_client.get(f"/api/v1/requests/{req['id']}/original", headers=h_owner)
assert r.status_code == 200 and r.content == minimal_pdf()
assert r.headers["content-type"].startswith("application/octet-stream")
assert "sandbox" in r.headers["content-security-policy"]
r = admin_client.post("/api/v1/requests/upload", headers=h_owner,
files={"file": ("umowa.docx", b"PK\x03\x04", "application/octet-stream")})
assert r.status_code == 422 and r.json()["code"] == "pdf_only"
def test_signing_is_for_moderators_and_needs_a_certificate(admin_client, make_user, monkeypatch):
from app import config
owner = make_user("asker")
req = _upload(admin_client, bearer(owner["token"]))
r = admin_client.post(f"/api/v1/requests/{req['id']}/sign", headers=bearer(owner["token"]))
assert r.status_code == 403
monkeypatch.setattr(config.get_settings(), "signing_pkcs12_path", "")
r = admin_client.post(f"/api/v1/requests/{req['id']}/sign")
assert r.status_code == 409 and r.json()["code"] == "signing_unconfigured"
assert admin_client.get(f"/api/v1/requests/{req['id']}").json()["status"] == "draft"
def test_sign_verify_lists_stats_and_event(admin_client, make_user, signer):
owner = make_user("signee")
h_owner = bearer(owner["token"])
req = _upload(admin_client, h_owner, title=f"Do podpisu {RUN}")
def tiles(h):
body = admin_client.get("/api/v1/stats", headers=h).json()
stats_contract.validate_response(body)
return {t["key"]: t["count"] for t in body["tiles"]}
def lists(h):
return (len(admin_client.get("/api/v1/requests?view=todo", headers=h).json()),
len(admin_client.get("/api/v1/requests?view=signed", headers=h).json()))
before = tiles(h_owner)
assert (before["to_sign"], before["signed"]) == lists(h_owner) == (1, 0)
r = admin_client.post(f"/api/v1/requests/{req['id']}/sign")
assert r.status_code == 200, r.text
done = r.json()
assert done["status"] == "signed" and done["signed"]["name"] == "umowa.podpisany.pdf"
assert "Parafa Test Signer" in done["signed"]["signer"]
after = tiles(h_owner)
assert (after["to_sign"], after["signed"]) == lists(h_owner) == (0, 1)
admin_tiles = tiles({})
assert (admin_tiles["to_sign"], admin_tiles["signed"]) == lists({})
# The owner can fetch and verify the signed result.
signed = admin_client.get(f"/api/v1/requests/{req['id']}/signed", headers=h_owner)
assert signed.status_code == 200 and signed.content != minimal_pdf()
report = admin_client.get(f"/api/v1/requests/{req['id']}/verify", headers=h_owner).json()
assert report["count"] == 1 and report["all_valid"] and report["signatures"][0]["trusted"]
r = admin_client.post("/api/v1/verify", headers=h_owner,
files={"file": ("x.pdf", signed.content, "application/pdf")})
assert r.status_code == 200 and r.json()["all_valid"]
assert admin_client.post(f"/api/v1/requests/{req['id']}/sign").status_code == 409
rows = _event(req["id"])
assert len(rows) == 1 and rows[0][0] == "document.signed" and rows[0][1] == "parafa"
assert rows[0][2]["sha256"] == done["signed"]["sha256"]
def test_a_document_that_cannot_be_signed_is_failed_and_retryable(admin_client, signer):
broken = b"%PDF-1.7\nnot really a pdf\n"
req = _upload(admin_client, {}, data=broken)
r = admin_client.post(f"/api/v1/requests/{req['id']}/sign")
assert r.status_code in (409, 422), r.text
after = admin_client.get(f"/api/v1/requests/{req['id']}").json()
assert after["status"] == "failed" and after["error"] and after["can_sign"]
assert after["id"] in {x["id"] for x in admin_client.get("/api/v1/requests?view=todo").json()}
class _FakeGalena:
"""Galena's three calls Parafa makes, in memory: file-info, raw at a commit, upload."""
service = "Galena"
def __init__(self, data: bytes):
self.versions = {"a" * 40: data}
self.head = "a" * 40
self.uploads = []
def request(self, method, path, *, token, params=None, body=None, content_type=None,
headers=None, accept="application/json", json=None):
from dredd_core.module_client import ModuleResponse
assert token, "every Galena call carries the person's token"
if path.endswith("/file-info"):
return ModuleResponse(200, {}, _json.dumps(
{"exists": True, "last_commit": {"sha": self.head}}).encode())
if path.endswith("/raw"):
return ModuleResponse(200, {}, self.versions[params["ref"]])
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]
data = part.rsplit(b"\r\n--", 1)[0]
self.head = (uuid.uuid4().hex + uuid.uuid4().hex)[:40]
self.versions[self.head] = data
self.uploads.append(self.head)
return ModuleResponse(201, {}, _json.dumps(
{"path": "umowy/a.pdf", "sha": self.head}).encode())
raise AssertionError(path)
def test_a_galena_document_is_signed_back_as_a_new_version(admin_client, signer, monkeypatch):
from app.services import signing as service
fake = _FakeGalena(minimal_pdf("Galena"))
monkeypatch.setattr(service, "galena", lambda: fake)
r = admin_client.post("/api/v1/requests/document",
json={"document_id": str(uuid.uuid4()), "path": "umowy/a.pdf"})
assert r.status_code == 201, r.text
req = r.json()
assert req["ref"]["kind"] == "document" and req["ref"]["commit_sha"] == "a" * 40
r = admin_client.post(f"/api/v1/requests/{req['id']}/sign")
assert r.status_code == 200, r.text
assert fake.uploads and r.json()["signed"]["commit_sha"] == fake.uploads[-1]
rows = _event(req["id"])
assert rows[0][2]["commit_sha"] == fake.uploads[-1] and rows[0][2]["signed_from"] == "a" * 40
bad = admin_client.post("/api/v1/requests/document",
json={"document_id": str(uuid.uuid4()), "path": "umowy/a.docx"})
assert bad.status_code == 422 and bad.json()["code"] == "pdf_only"
monkeypatch.setattr(service, "galena", lambda: None)
off = admin_client.post("/api/v1/requests/document",
json={"document_id": str(uuid.uuid4()), "path": "umowy/b.pdf"})
assert off.status_code == 409 and off.json()["code"] == "galena_disabled"
@pytest.mark.parametrize(("method", "path", "body"), [
("GET", "/api/v1/requests/not-a-uuid", None),
("GET", "/api/v1/requests?view=bogus", None),
("POST", "/api/v1/requests/document", {"document_id": "nope", "path": "a.pdf"}),
("POST", "/api/v1/users/not-a-uuid/deactivate", None),
("PUT", "/api/v1/admin/settings", {"values": "not-a-dict"}),
])
def test_bad_input_is_422_never_500(admin_client, method, path, body):
r = admin_client.request(method, path, json=body)
+1 -8
View File
@@ -30,8 +30,7 @@ def test_core_tables_are_registered():
def test_the_apps_own_tables_are_registered():
"""A model missing from `app/models/__init__.py` silently gets no table."""
assert {"signing_request", "module_event", "module_event_cursor",
"module_event_receipt"} <= set(_metadata().tables)
assert {"module_event", "module_event_cursor", "module_event_receipt"} <= set(_metadata().tables)
def test_every_model_enum_is_derived_for_the_migration():
@@ -47,12 +46,6 @@ def test_every_model_enum_is_derived_for_the_migration():
)
def test_the_app_creates_no_enum_type_of_its_own():
"""Parafa keeps its states as text with a CHECK; only core's types are derived."""
table = _metadata().tables["signing_request"]
assert not any(isinstance(c.type, PGEnum) for c in table.columns)
def test_every_evidence_table_is_a_real_table():
"""The runtime grants revoke only on tables that exist, so a misspelt evidence table would be
skipped silently and stay fully writable for the runtime role."""
-150
View File
@@ -1,150 +0,0 @@
"""DB-free tests of the signing domain: PAdES signing and verification with a throwaway certificate
made at test time (tests/pki.py, never committed), the PDF-only rule, the event payload and the
stats shape."""
from __future__ import annotations
import uuid
import pytest
from dredd_core import events, stats_contract
from dredd_core.document_ref import DocumentRef, FileRef
from pki import make_signer, minimal_pdf
from app import config
from app.errors import ConflictError, ValidationError
from app.services import pades, signing
@pytest.fixture
def signer_env(tmp_path, monkeypatch):
p12, passphrase, pem = make_signer(tmp_path / "pki")
monkeypatch.setenv("SIGNING_PKCS12_PATH", str(p12))
secret = tmp_path / "pass.txt"
secret.write_text(passphrase + "\n", encoding="utf-8")
monkeypatch.setenv("SIGNING_PKCS12_PASSPHRASE_FILE", str(secret))
config.get_settings.cache_clear()
yield pem
config.get_settings.cache_clear()
@pytest.fixture
def no_signer(monkeypatch):
for name in ("SIGNING_PKCS12_PATH", "SIGNING_PKCS12_PASSPHRASE", "SIGNING_PKCS12_PASSPHRASE_FILE",
"SIGNING_TRUST_ROOTS"):
monkeypatch.delenv(name, raising=False)
config.get_settings.cache_clear()
yield
config.get_settings.cache_clear()
def test_sign_then_verify_is_intact_valid_pades(signer_env):
signed = pades.sign(minimal_pdf(), reason="Akceptacja")
report = pades.verify(signed)
assert report["count"] == 1 and report["all_valid"]
sig = report["signatures"][0]
assert sig["intact"] and sig["valid"] and sig["pades"]
assert sig["coverage"] == "ENTIRE_FILE"
assert "Parafa Test Signer" in sig["signer"]
assert not sig["trusted"] and not report["trust_configured"] # no anchors configured
assert report["revocation_checked"] is False
def test_trust_roots_make_it_trusted(signer_env, monkeypatch):
monkeypatch.setenv("SIGNING_TRUST_ROOTS", str(signer_env))
config.get_settings.cache_clear()
report = pades.verify(pades.sign(minimal_pdf()))
assert report["signatures"][0]["trusted"] and report["trust_configured"]
def test_a_second_signature_keeps_the_first_intact(signer_env):
twice = pades.sign(pades.sign(minimal_pdf()))
report = pades.verify(twice)
assert report["count"] == 2 and report["all_valid"]
assert [s["field"] for s in report["signatures"]] == ["Parafa1", "Parafa2"]
def test_tampering_is_detected(signer_env):
signed = bytearray(pades.sign(minimal_pdf("Kwota 1000 zl")))
at = signed.index(b"1000")
signed[at:at + 4] = b"9000"
sig = pades.verify(bytes(signed))["signatures"][0]
assert not (sig["intact"] and sig["valid"])
def test_an_unsigned_pdf_has_no_signatures():
report = pades.verify(minimal_pdf())
assert report == {"signatures": [], "count": 0, "all_valid": False,
"trust_configured": False, "revocation_checked": False}
@pytest.mark.parametrize("name,data,code", [
("umowa.docx", b"PK\x03\x04", "pdf_only"),
("umowa.pdf", b"", "file_empty"),
("umowa.pdf", b"PK\x03\x04 not a pdf", "format_mismatch"),
])
def test_only_pdfs_are_accepted(name, data, code):
with pytest.raises(ValidationError) as caught:
pades.check_pdf(name, data)
assert caught.value.extra["code"] == code
def test_verify_refuses_a_non_pdf():
with pytest.raises(ValidationError):
pades.verify(b"hello")
def test_unconfigured_signing_is_a_409(no_signer):
assert not pades.configured()
with pytest.raises(ConflictError) as caught:
pades.signer()
assert caught.value.extra["code"] == "signing_unconfigured"
def test_a_wrong_passphrase_is_a_409(tmp_path, monkeypatch, no_signer):
p12, _, _ = make_signer(tmp_path / "pki")
monkeypatch.setenv("SIGNING_PKCS12_PATH", str(p12))
monkeypatch.setenv("SIGNING_PKCS12_PASSPHRASE", "wrong")
config.get_settings.cache_clear()
with pytest.raises(Exception): # noqa: B017 - pyHanko/cryptography's own error, or our 409
pades.signer()
def test_signed_name():
assert pades.signed_name("umowa.pdf") == "umowa.podpisany.pdf"
assert pades.signed_name("A.PDF") == "A.podpisany.pdf"
class _Row:
"""Just the attributes `event_payload` reads."""
def __init__(self, ref):
self.id = uuid.uuid4()
self.ref = ref
self.signed_sha256 = "a" * 64
self.signed_file_id = uuid.uuid4()
self.signed_commit_sha = "c" * 40
def test_event_payload_is_identifiers_only():
doc = DocumentRef(document_id=uuid.uuid4(), path="umowy/a.pdf", commit_sha="b" * 40,
sha256="d" * 64)
payload = events.check_payload(signing.event_payload(_Row(doc)))
assert set(payload) == {"request_id", "sha256", "file_id", "document_id", "commit_sha",
"signed_from"}
plain = FileRef(file_id=uuid.uuid4(), sha256="e" * 64, size=10, name="a.pdf")
assert set(events.check_payload(signing.event_payload(_Row(plain)))) == {
"request_id", "sha256", "file_id"}
def test_stats_answer_the_contract(monkeypatch):
monkeypatch.setattr(signing, "count", lambda db, user, view: {"todo": 3, "signed": 5}[view])
body = signing.module_stats(None, None)
stats_contract.validate_response(body)
assert [(t["key"], t["count"], t["link"]) for t in body["tiles"]] == [
("to_sign", 3, "todo"), ("signed", 5, "signed")]
assert body["module"] == "parafa"
def test_views_match_the_status_vocabulary():
from app.models.signing import STATUSES
assert set(signing.VIEWS["todo"]) | set(signing.VIEWS["signed"]) == set(STATUSES)
-4
View File
@@ -51,10 +51,6 @@ services:
- "${PARAFA_PORT:-8121}:8000"
volumes:
- parafa-data:/data
# The operator's signing certificate (PKCS#12) and its passphrase file, read-only, from a
# directory OUTSIDE the repo (never committed, never baked into the image). Point
# SIGNING_PKCS12_PATH / SIGNING_PKCS12_PASSPHRASE_FILE at the files under /run/parafa-signer.
- ${PARAFA_SIGNER_DIR:-./signer}:/run/parafa-signer:ro
depends_on:
migrate:
condition: service_completed_successfully
+3 -305
View File
@@ -197,7 +197,6 @@ const I18N = {
'Motyw': 'Theme',
'Język': 'Language',
'Konto': 'Account',
'Szukaj…': 'Search…',
'Motyw: systemowy': 'Theme: system',
'Motyw: jasny': 'Theme: light',
'Motyw: ciemny': 'Theme: dark',
@@ -219,54 +218,6 @@ const I18N = {
'Nie znaleziono strony.': 'Page not found.',
'Zapisano.': 'Saved.',
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
'Do podpisu': 'To sign',
'Podpisane': 'Signed',
'Weryfikacja': 'Verification',
'Weryfikacja podpisu': 'Signature verification',
'Sprawdź podpisy w dowolnym pliku PDF. Plik nie jest zapisywany.': 'Check the signatures in any PDF. The file is not stored.',
'Zweryfikuj podpis': 'Verify a signature',
'Zweryfikuj': 'Verify',
'Nowy wniosek': 'New request',
'Brak wniosków.': 'No requests.',
'Wnioski': 'Requests',
'Tytuł': 'Title',
'Plik': 'File',
'Plik PDF': 'PDF file',
'Źródło': 'Source',
'Zmieniono': 'Changed',
'do podpisu': 'to sign',
'podpisany': 'signed',
'nieudany': 'failed',
'plik': 'file',
'Oryginał': 'Original',
'Podpisany plik': 'Signed file',
'Podpisz': 'Sign',
'Podpisano.': 'Signed.',
'Podpis': 'Signature',
'Podpisano': 'Signed at',
'Podpisał(a)': 'Signed by',
'Certyfikat': 'Certificate',
'Wersja w Galenie': 'Galena version',
'Wnioskodawca': 'Requested by',
'Powód podpisu': 'Reason',
'Tylko pliki PDF.': 'PDF files only.',
'albo dokument z Galeny': 'or a document in Galena',
'Identyfikator projektu': 'Project id',
'Ścieżka pliku': 'File path',
'Wybierz plik PDF.': 'Choose a PDF file.',
'Plik zostanie podpisany certyfikatem operatora (PAdES). Podpisu nie da się wycofać.': 'The file will be signed with the operator\'s certificate (PAdES). A signature cannot be withdrawn.',
'Pole': 'Field',
'Podpisujący': 'Signer',
'Czas': 'Time',
'Nienaruszony': 'Intact',
'Poprawny': 'Valid',
'Zaufany': 'Trusted',
'Zakres': 'Coverage',
'tak': 'yes',
'nie': 'no',
'Wszystkie podpisy są nienaruszone i poprawne.': 'Every signature is intact and valid.',
'Co najmniej jeden podpis jest naruszony albo niepoprawny.': 'At least one signature is broken or invalid.',
'Ten plik PDF nie ma podpisów.': 'This PDF has no signatures.',
};
let LANG = (function () {
@@ -420,9 +371,6 @@ const isModerator = () => !!(state.user && state.user.is_moderator);
/* ── navigation ─────────────────────────────────────────────────────────── */
const NAV = [
{ hash: '#/', icon: 'dashboard', label: 'Pulpit' },
{ hash: '#/todo', icon: 'signature', label: 'Do podpisu', badge: 'todo' },
{ hash: '#/signed', icon: 'check', label: 'Podpisane' },
{ hash: '#/verify', icon: 'shield', label: 'Weryfikacja' },
];
function renderNav(counts) {
@@ -472,13 +420,10 @@ function parseHash() {
async function router() {
if (!state.user) return;
const C = $('content');
const { seg, q } = parseHash();
const { seg } = parseHash();
C.innerHTML = '<div class="faint">Wczytywanie…</div>';
try {
if (!seg.length) await viewDashboard(C);
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] === 'admin') await viewAdmin(C);
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
} catch (ex) {
@@ -492,120 +437,8 @@ async function router() {
/* ── dashboard ──────────────────────────────────────────────────────────── */
async function viewDashboard(C) {
const d = await api('GET', '/dashboard');
const c = d.cards || {};
state.counts = { todo: c.todo };
state.galena = !!d.galena;
setCrumb([{ label: 'Pulpit' }]);
const tiles = [
{ k: 'Do podpisu', v: c.todo ?? 0, href: '#/todo' },
{ k: 'Podpisane', v: c.signed ?? 0, href: '#/signed' },
];
const signer = d.signing_configured
? `<div class="banner">Certyfikat operatora: ${esc(d.signer || '—')}</div>`
: '<div class="banner warn">Podpisywanie nie jest skonfigurowane: operator nie wskazał certyfikatu (SIGNING_PKCS12_PATH). Wnioski można składać i weryfikować podpisy.</div>';
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email,
`<button class="btn" onclick="location.hash='#/verify'">${svg(ICN.shield)}Zweryfikuj podpis</button>`
+ `<button class="btn primary" onclick="openRequestNew()">${svg(ICN.plus)}Nowy wniosek</button>`)
+ signer
+ `<div class="tiles" style="margin-top:14px">${tiles.map((t) => `<a class="tile" href="${t.href}"><div class="k">${esc(t.k)}</div><div class="v">${esc(String(t.v))}</div></a>`).join('')}</div>`
+ `<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' };
function statusChip(s) {
const cls = s === 'signed' ? 'ok' : (s === 'failed' ? 'err' : '');
return `<span class="chip ${cls}">${esc(STATUS_LABEL[s] || s)}</span>`;
}
function sourceLabel(r) {
return r.on_galena ? 'Galena' : 'plik';
}
function requestTable(rows) {
if (!rows.length) return '<div class="empty">Brak wniosków.</div>';
return `<div class="tablewrap"><table class="rt"><thead><tr>
<th>Tytuł</th><th>Plik</th><th>Źródło</th><th>Status</th><th>Zmieniono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/requests/${encodeURIComponent(r.id)}'">
<td><div>${esc(r.title)}${r.owner_name && !r.mine ? `<div class="faint tiny">${esc(r.owner_name)}</div>` : ''}</div></td>
<td class="tiny"${lbl('Plik')}>${esc(r.name)}</td>
<td class="tiny"${lbl('Źródło')}>${esc(sourceLabel(r))}</td>
<td${lbl('Status')}>${statusChip(r.status)}</td>
<td class="faint tiny"${lbl('Zmieniono')}>${fmtDate(r.updated_at)}</td>
</tr>`).join('')}</tbody></table></div>`;
}
/* ── the two lists ──────────────────────────────────────────────────────── */
async function viewRequests(C, view, q) {
const title = view === 'signed' ? 'Podpisane' : 'Do podpisu';
const params = new URLSearchParams({ view });
if (q.q) params.set('q', q.q);
const rows = await api('GET', '/requests?' + params);
setCrumb([{ label: title }]);
C.innerHTML = pageHead(title, rows.length + '',
`<button class="btn primary" onclick="openRequestNew()">${svg(ICN.plus)}Nowy wniosek</button>`)
+ `<div class="toolbar"><input type="search" id="rq" placeholder="Szukaj…" value="${esc(q.q || '')}" /></div>`
+ (rows.length ? `<div class="card">${requestTable(rows)}</div>` : '<div class="empty">Brak wniosków.</div>');
$('rq').addEventListener('change', () => {
const v = $('rq').value.trim();
location.hash = '#/' + view + (v ? '?q=' + encodeURIComponent(v) : '');
});
}
/* ── one request ────────────────────────────────────────────────────────── */
async function viewRequest(C, id) {
const r = await api('GET', '/requests/' + encodeURIComponent(id));
const listHref = r.status === 'signed' ? '#/signed' : '#/todo';
setCrumb([{ label: r.status === 'signed' ? 'Podpisane' : 'Do podpisu', href: listHref }, { label: r.title }]);
const s = r.signed;
const rid = esc(r.id);
C.innerHTML = pageHead(r.title, r.name,
`<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_sign ? `<button class="btn primary" onclick="confirmSign('${rid}')">${svg(ICN.signature)}Podpisz</button>` : ''))
+ (r.status === 'failed' && r.error ? `<div class="banner err">Ostatnia próba podpisu nie powiodła się: ${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: ' + r.ref.path : 'plik: ' + r.name)}
${field('Wnioskodawca', r.owner_name)}
${field('Powód podpisu', r.reason)}
${field('Utworzono', fmtDateTime(r.created_at))}
${field('SHA-256', r.ref.sha256)}
</div>
${r.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(r.note)}</div></div>` : ''}
</div>`
+ (s ? `<div class="card" style="margin-top:14px"><h3>Podpis</h3><div class="grid3">
${field('Podpisano', fmtDateTime(s.at))}
${field('Podpisał(a)', s.by_name)}
${field('Certyfikat', s.signer)}
${field('Plik', s.name)}
${field('SHA-256', s.sha256)}
${field('Wersja w Galenie', s.commit_sha ? s.commit_sha.slice(0, 12) : null)}
</div></div>` : '')
+ '<div id="verifyOut"></div>';
}
function confirmSign(id) {
modal('Podpisz', '',
'<div class="banner warn">Plik zostanie podpisany certyfikatem operatora (PAdES). Podpisu nie da się wycofać.</div>',
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="doSign('${esc(id)}')">Podpisz</button>`);
}
function doSign(id) {
guard(async () => {
try {
await api('POST', '/requests/' + encodeURIComponent(id) + '/sign');
closeModal();
toast('Podpisano.');
} finally {
await router();
}
});
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email);
}
/* Bytes come back as a download only (core's rule for untrusted bytes), fetched with the session
@@ -648,106 +481,6 @@ async function apiForm(path, form) {
return data;
}
/* ── verification ───────────────────────────────────────────────────────── */
function verifyReport(rep) {
const sigs = rep.signatures || [];
const head = sigs.length
? (rep.all_valid ? '<div class="banner">Wszystkie podpisy są nienaruszone i poprawne.</div>'
: '<div class="banner err">Co najmniej jeden podpis jest naruszony albo niepoprawny.</div>')
: '<div class="banner warn">Ten plik PDF nie ma podpisów.</div>';
const notes = `<div class="faint tiny" style="margin-top:8px">${rep.trust_configured
? 'Zaufanie sprawdzane wobec certyfikatów wskazanych przez operatora.'
: 'Operator nie wskazał zaufanych certyfikatów: „zaufany” będzie zawsze „nie”.'} Odwołania certyfikatów nie są sprawdzane.</div>`;
const yes = (v) => (v ? 'tak' : 'nie');
const rows = sigs.map((s) => `<tr>
<td${lbl('Pole')}>${esc(s.field || '—')}</td>
<td${lbl('Podpisujący')}>${esc(s.signer || '—')}</td>
<td class="tiny"${lbl('Czas')}>${esc(s.signed_at ? fmtDateTime(s.signed_at) : '—')}</td>
<td${lbl('Nienaruszony')}>${esc(yes(s.intact))}</td>
<td${lbl('Poprawny')}>${esc(yes(s.valid))}</td>
<td${lbl('Zaufany')}>${esc(yes(s.trusted))}</td>
<td class="tiny"${lbl('Zakres')}>${esc(s.coverage || '—')}${s.error ? `<div class="faint">${esc(s.error)}</div>` : ''}</td>
</tr>`).join('');
return head + (sigs.length ? `<div class="card" style="margin-top:10px"><div class="tablewrap"><table class="rt"><thead><tr>
<th>Pole</th><th>Podpisujący</th><th>Czas</th><th>Nienaruszony</th><th>Poprawny</th><th>Zaufany</th><th>Zakres</th>
</tr></thead><tbody>${rows}</tbody></table></div></div>` : '') + notes;
}
function verifyRequest(id) {
guard(async () => {
const rep = await api('GET', '/requests/' + encodeURIComponent(id) + '/verify');
const out = $('verifyOut');
out.innerHTML = `<div class="card" style="margin-top:14px"><h3>Weryfikacja</h3>${verifyReport(rep)}</div>`;
localize(out);
}).then(() => {});
}
async function viewVerify(C) {
setCrumb([{ label: 'Weryfikacja' }]);
C.innerHTML = pageHead('Weryfikacja podpisu', 'Sprawdź podpisy w dowolnym pliku PDF. Plik nie jest zapisywany.')
+ `<div class="card"><label class="field">Plik PDF<input type="file" id="vfFile" accept=".pdf,application/pdf" /></label>
<div style="margin-top:12px"><button class="btn primary" id="vfGo">${svg(ICN.shield)}Zweryfikuj</button></div></div>
<div id="vfOut" style="margin-top:14px"></div>`;
$('vfGo').addEventListener('click', async () => {
const f = $('vfFile').files[0];
const out = $('vfOut');
if (!f) { out.innerHTML = '<div class="banner warn">Wybierz plik PDF.</div>'; localize(out); return; }
const form = new FormData();
form.append('file', f, f.name);
out.innerHTML = '<div class="faint">Wczytywanie…</div>';
try {
out.innerHTML = verifyReport(await apiForm('/verify', form));
} catch (ex) {
out.innerHTML = `<div class="banner err">${esc(ex.message)}</div>`;
}
localize(out);
});
}
/* ── a new request ──────────────────────────────────────────────────────── */
function openRequestNew() {
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>`
: '';
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">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>
<button class="btn primary" onclick="saveRequestNew()">Zapisz</button>`);
}
function saveRequestNew() {
guard(async () => {
const title = $('nqTitle').value.trim() || null;
const reason = $('nqReason').value.trim() || null;
const note = $('nqNote').value.trim() || null;
const f = $('nqFile').files[0];
const doc = $('nqDoc') ? $('nqDoc').value.trim() : '';
let r;
if (f) {
const form = new FormData();
form.append('file', f, f.name);
if (title) form.append('title', title);
if (reason) form.append('reason', reason);
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 });
} else {
throw new Error('Wybierz plik PDF.');
}
closeModal();
toast('Zapisano.');
location.hash = '#/requests/' + encodeURIComponent(r.id);
await router();
});
}
/* ── administration ─────────────────────────────────────────────────────── */
async function viewAdmin(C) {
setCrumb([{ label: 'Administracja' }]);
@@ -860,38 +593,8 @@ function guard(fn) {
});
}
/* ── command palette ────────────────────────────────────────────────────── */
function openSearch() {
modal('', '', '', '');
$('modalRoot').innerHTML = `<div class="scrim search-scrim" onclick="if(event.target===this)closeModal()">
<div class="search-modal" role="dialog" aria-modal="true">
<div class="sin">${svg(ICN.search, 18)}<input id="sq" placeholder="Szukaj…" autocomplete="off" /></div>
<div class="search-results" id="sres"></div>
<div class="shint">Esc</div>
</div></div>`;
const input = $('sq');
input.focus();
let timer = null;
const run = async () => {
const q = input.value.trim();
if (!q) { $('sres').innerHTML = ''; return; }
try {
const rows = await api('GET', '/requests?q=' + encodeURIComponent(q));
$('sres').innerHTML = rows.length
? `<div class="sgroup">Wnioski</div>` + rows.slice(0, 12).map((r) =>
`<button class="sitem" onclick="closeModal();location.hash='#/requests/${encodeURIComponent(r.id)}'">
<span class="ic">${svg(ICN.file)}</span>
<span class="sb"><span class="st">${esc(r.title)}</span>
<span class="ss">${esc(r.name)} · ${esc(STATUS_LABEL[r.status] || r.status)}</span></span></button>`).join('')
: '<div class="search-empty">Brak wyników</div>';
localize($('sres'));
} catch { $('sres').innerHTML = ''; }
};
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 180); });
}
/* ── account sheet ──────────────────────────────────────────────────────── */
/* On a phone the top bar drops search, theme and language (`.js-tool`) to leave room for the
/* On a phone the top bar drops theme and language (`.js-tool`) to leave room for the
breadcrumb — so they live here too (`.m-only`), or a phone user could never reach them. */
const THEME_LABEL = { system: 'Motyw: systemowy', light: 'Motyw: jasny', dark: 'Motyw: ciemny' };
@@ -901,7 +604,6 @@ function openAccount() {
`<button class="appcard ${cls || ''}" onclick="${action}"><span class="ai">${svg(icon)}</span><span class="an">${esc(label)}</span></button>`;
modal(state.user ? (state.user.full_name || state.user.email) : '', state.user ? state.user.email : '',
'<div class="applist">'
+ row(ICN.search, 'Szukaj…', 'closeModal();openSearch()', 'm-only')
+ row(TH[mode] || TH.system, THEME_LABEL[mode] || THEME_LABEL.system, 'cycleTheme();openAccount()', 'm-only')
+ row(ICN.globe, LANG === 'pl' ? 'Język: polski' : 'Język: angielski', 'cycleLang()', 'm-only')
+ row(ICN.logout, 'Wyloguj się', 'closeModal();doLogout()')
@@ -946,14 +648,10 @@ window.addEventListener('DOMContentLoaded', () => {
$('navToggle').innerHTML = svg(ICN.menu, 18);
$('navToggle').addEventListener('click', openDrawer);
$('navScrim').addEventListener('click', closeDrawer);
const searchBtn = $('aSearch');
searchBtn.querySelector('.si').innerHTML = svg(ICN.search, 14);
searchBtn.addEventListener('click', openSearch);
$('aUser').addEventListener('click', openAccount);
window.addEventListener('hashchange', router);
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openSearch(); }
if (e.key === 'Escape') closeModal();
});
-4
View File
@@ -76,10 +76,6 @@
<button class="iconbtn" id="navToggle" title="Menu"></button>
<div class="crumb" id="crumb"></div>
<div class="spacer"></div>
<button class="searchbar js-tool" id="aSearch" title="Szukaj… (Ctrl+K)">
<span class="si"></span><span class="sp">Szukaj…</span><kbd>Ctrl K</kbd>
</button>
<span class="vdiv js-tool"></span>
<button class="iconbtn js-theme js-tool" id="aTheme" title="Motyw"></button>
<button class="iconbtn txt js-tool" id="aLang" title="Język" data-no-i18n>PL</button>
<button type="button" class="avatar" id="aUser" title="Konto" aria-label="Konto" aria-haspopup="dialog">?</button>