Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1f8f9dfba | ||
|
|
b188f9cc18 | ||
|
|
23c842b418 | ||
|
|
32aa86682e | ||
|
|
433e083dae | ||
|
|
fb4867c1ad | ||
|
|
b9d7f83b74 | ||
|
|
fbbbdbc53d | ||
|
|
6cd08ada43 | ||
|
|
471b871248 | ||
|
|
80d5058fa4 | ||
|
|
cb34855f9b | ||
|
|
ab5c16670c | ||
|
|
57d39598eb | ||
|
|
f8afd24ef6 | ||
|
|
4c5ecf4cde | ||
|
|
14e51728f5 |
@@ -1,5 +1,11 @@
|
||||
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
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
|
||||
@@ -17,7 +17,7 @@ one identity / session / auth / audit core, one org tree, one permission model,
|
||||
| `.security` | Argon2id password hashing, opaque tokens, passphrase KDF |
|
||||
| `.audit` | `record()` — the append-only audit writer |
|
||||
| `.db` | `make_engine` / `make_session_factory` with hardened defaults; libpq-style `sslmode` / `sslrootcert` URL parameters become a pg8000 TLS context (`ssl_context_for`, `strip_tls_params`); the family's TLS rule (`is_local_host`, `require_verified_tls`) |
|
||||
| `.schema` | `migration_preflight_sql()` — the first statement of an app's first revision: refuse the wrong migrating role before anything is created; `enum_types()` / `create_enum_types()` — the DDL prerequisite for `create_all`; `own_tables()` — which tables are this app's own; `runtime_grants_sql()` — the runtime role's least-privilege grants as one idempotent `DO` block; `shared_identity_grants_sql()` and `account_delete_guard_sql()` for a shared identity schema |
|
||||
| `.schema` | `migration_preflight_sql()` — the first statement of an app's first revision: refuse the wrong migrating role before anything is created; `enum_types()` / `create_enum_types()` — the DDL prerequisite for `create_all`; `own_tables()` — which tables are this app's own; `runtime_grants_sql()` — the runtime role's least-privilege grants as one idempotent `DO` block; `shared_identity_grants_sql()`, `account_delete_guard_sql()` and `session_update_guard_sql()` for a shared identity schema |
|
||||
| `.identity_schema` | `assert_identity_schema()` (a boot assertion), `create_identity_tables()`, and the merge helpers `repoint_identity_fks_sql()` / `orphan_rows_sql()` |
|
||||
| `.provisioning` | `provision()` / `provision_sql()` — one app's schema and roles in the shared managed database, run live or rendered as SQL |
|
||||
| `.managed` | `python -m dredd_core.managed provision` (that routine as a command), `check` (read-only managed-Postgres preflight: cross-schema isolation, and the shared identity allowlist) and `emulate` (TEST-ONLY managed-Postgres lookalike) |
|
||||
@@ -41,7 +41,7 @@ It is a **private** repo, so pin it by tag (the newest release; the /dredd scaff
|
||||
and give CI a read-only token:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.25.0
|
||||
```
|
||||
|
||||
```yaml
|
||||
@@ -328,7 +328,9 @@ Phase B, in the owning app's revision:
|
||||
|
||||
```python
|
||||
from dredd_core.identity_schema import create_identity_tables
|
||||
from dredd_core.schema import account_delete_guard_sql, shared_identity_grants_sql
|
||||
from dredd_core.schema import (
|
||||
account_delete_guard_sql, session_update_guard_sql, shared_identity_grants_sql,
|
||||
)
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
@@ -341,6 +343,8 @@ def upgrade() -> None:
|
||||
migrator_roles=("galena_migrator", "sygna_migrator", "counsel_migrator"),
|
||||
))
|
||||
op.execute(account_delete_guard_sql("dredd", owner_role="atrium_migrator"))
|
||||
op.execute(session_update_guard_sql("dredd", owner_role="atrium_migrator",
|
||||
writer_role="atrium_app"))
|
||||
```
|
||||
|
||||
| role | `app_user` | `session` | `module_permission` |
|
||||
@@ -367,6 +371,13 @@ def upgrade() -> None:
|
||||
identity owner, which holds `DELETE` by owning the table — with a `BEFORE DELETE OR TRUNCATE`
|
||||
trigger, because the cross-schema `ON DELETE CASCADE`s mean one `DELETE` would destroy rows in every
|
||||
other app's schema whatever privileges the deleting role holds there.
|
||||
- **No module revives or prolongs a credential.** The three-column `UPDATE` on `session` covers every
|
||||
row and every value, so on its own it would let any module set `revoked_at = NULL` on a session the
|
||||
hub revoked, or push the administrator's `expires_at` to `infinity`. `session_update_guard_sql`
|
||||
adds a row-level `BEFORE UPDATE` trigger that, for every role but the owner and the writer, refuses
|
||||
any change to `revoked_at` once it is set, any later `expires_at` except a live app token sliding to
|
||||
at most `idle_days` from now, and a change to any other column. Signing out, `last_seen_at` and the
|
||||
slide keep working unchanged.
|
||||
|
||||
The block **revokes before it grants**, so it is authoritative rather than additive: a column
|
||||
privilege somebody added by hand is gone after a re-run. It refuses to run as anyone but
|
||||
@@ -864,10 +875,11 @@ caller's decision**, passed as `is_admin`: the hub passes `app_user.is_admin`, a
|
||||
may" from "an administrator may, you may not"; `usable_providers`, `visible` (everything for an
|
||||
administrator, the usable ones for everyone else, nothing at `nobody`), `for_reading` (404, never 403),
|
||||
`known_model_ids`. **Writes** (the hub, or a standalone app): `create`, `update` (partial; `clear=`
|
||||
names what to empty; `kind` never changes), `disable` (never delete — a run records its provider),
|
||||
names what to empty; `kind` never changes), `disable` (the default way out — a run records its provider), `delete_unused` (a disabled provider
|
||||
no run points at; 409 `provider_still_active` / `provider_in_use` otherwise),
|
||||
`set_policy`. All refusals are coded `ValidationError` / `NotFoundError` (`extra.code`, Polish
|
||||
`detail`, English `extra.en`; `MESSAGE_CODES`). Every write is audited through `dredd_core.audit`:
|
||||
`model_provider.create` / `.update` / `.disable` / `.policy`, with a diff in which a key is only ever
|
||||
`model_provider.create` / `.update` / `.disable` / `.delete` / `.policy`, with a diff in which a key is only ever
|
||||
"set" / "replaced".
|
||||
|
||||
**The call target comes only from this table (SSRF).** A caller posts to `provider.base_url` as
|
||||
@@ -1274,7 +1286,8 @@ the payload is identifiers and numbers by construction, and a reader shows aggre
|
||||
* `event_grants_sql` gains `reader_roles` (default empty: the 0.20 block, unchanged in effect);
|
||||
`managed check` gains `--events-reader`. **Hub (Atrium)**: to admit Panorama's trends, add
|
||||
`panorama_app` to `reader_roles` in its event-grant revision.
|
||||
* K4 (the chat), planned as 0.23.0 in the Compass split plan, becomes **0.24.0**.
|
||||
* K4 (the chat), planned as 0.23.0 in the Compass split plan, was then moved to 0.24.0; 0.24.0
|
||||
went to the Workflow contract instead (below), and K4 takes a later release.
|
||||
|
||||
### 0.23.1 notes
|
||||
|
||||
@@ -1282,6 +1295,119 @@ the payload is identifiers and numbers by construction, and a reader shows aggre
|
||||
sends `api_key` or `clear={"api_key"}` (`base_url_needs_key`, 422). No schema change. Only the hub
|
||||
writes providers, so Atrium is the one app whose behaviour changes; the rest repin to stay identical.
|
||||
|
||||
### 0.23.2 notes
|
||||
|
||||
* New: `model_providers.delete_unused(db, actor=, provider=)` deletes a **disabled** provider that no
|
||||
run points at, its firm and personal keys with it, audited as `model_provider.delete`. Refused with
|
||||
409 `provider_still_active` or `provider_in_use`. "In use" is the database's answer, not a list in
|
||||
core: every module's foreign key to `model_provider` is `RESTRICT`, so a module core does not know
|
||||
is covered too. Why: an API key that expires after a day used to leave a provider on the list for
|
||||
good, disabled.
|
||||
* Grants: the writer (the hub) gains `DELETE` on `model_provider` (still nothing on the policy);
|
||||
`managed check` now requires it of the writer. **Hub (Atrium)**: no revision — `atrium-migrate`
|
||||
re-applies `model_provider_grants_sql` after every upgrade, so the repin grants it. No schema
|
||||
change; modules repin to stay identical.
|
||||
|
||||
## Workflow contract (0.24.0)
|
||||
|
||||
`dredd_core.workflow_contract` (opt-in, no tables; it does not even import `dredd_core.events`) is
|
||||
what the platform's **Workflow** module (slug `workflow`) and the modules around it agree on. Workflow
|
||||
holds every approval run — on a Galena document, on a plain file, on a request such as an expense —
|
||||
and the others talk to it in two ways only: they **read its events** from the shared `module_event`
|
||||
log (Galena moves a contract card to "zatwierdzona") and they **start a run** with the acting
|
||||
person's token.
|
||||
|
||||
* **Kinds:** `workflow.started`, `workflow.approved`, `workflow.rejected`, `workflow.cancelled`,
|
||||
`workflow.signed_on_paper` (`KINDS`; `STARTED`, `APPROVED`, …). `SOURCE_MODULE = "workflow"`.
|
||||
* **Who emits:** only Workflow's runtime role `workflow_app`. `source_module` is a label anyone may
|
||||
write, so a receiver passes `sources={kind: {"workflow_app"}}` for each kind it handles to
|
||||
`events.receive`, and calls `parse` on every payload: a row in the log is untrusted input.
|
||||
* **The payload** — identifiers and numbers only, inside `events.check_payload`: `run_id`,
|
||||
`actor_id`, `subject_kind` (`document` · `file` · `request`, `SUBJECT_KINDS`), an optional `stage`,
|
||||
and the subject's ids: a document's `module`, `document_id`, `commit_sha`, `sha256`; a file's
|
||||
`file_id`, `sha256`; a request's `request_type`. **No names, no content: a document's path and a
|
||||
file's name never enter the shared log** (every taking part module reads every event). The receiver
|
||||
reads the document by `document_id` + `commit_sha` through Galena's API.
|
||||
* **API:**
|
||||
* `payload(*, run_id, subject, request_type, actor_id, stage=None)` → `dict` — `subject` is a
|
||||
`DocumentRef` or a `FileRef`, or `None` with a `request_type`; exactly one of the two, else
|
||||
`ValidationError` (`subject_and_request_type` / `subject_missing`).
|
||||
* `parse(event_payload)` → `WorkflowEvent` (frozen: `run_id`, `subject_kind`, `document_module`,
|
||||
`document_id`, `commit_sha`, `file_id`, `sha256`, `request_type`, `actor_id`, `stage`; the
|
||||
fields of the other subject kinds are `None`). Anything malformed is a `ValidationError` with a
|
||||
`code`, never a `KeyError` or `TypeError`.
|
||||
* `WorkflowClient(client: ModuleClient).start(*, token, subject, template_id=None, note=None)` →
|
||||
`StartResult(run_id, link)` — `POST /runs` with **the acting person's token** (keyword-only, no
|
||||
default; empty → `ValidationError`), so Workflow's own authorization decides. The body carries
|
||||
the whole `document_ref.to_dict(subject)`, path included: it goes to one module's API, not into
|
||||
the log. An error answer raises as `ModuleResponse.raise_for_status` maps it; a 2xx without a
|
||||
valid `run_id` and a `#/…` `link` is a `ModuleCallError`. The link is a console route relative to
|
||||
Workflow's root (`#/runs/<run_id>`).
|
||||
* **The engine is not in core.** Templates, stages, who approves what: all of it lives in the
|
||||
Workflow module, the one home of every run (decided 2026-11-18). Core carries only what both sides
|
||||
must agree on, so a change to how approvals work is a release of one module, not of the family.
|
||||
|
||||
### 0.24.0 notes
|
||||
|
||||
* New, opt-in: `dredd_core.workflow_contract`. No schema change, no migration.
|
||||
* `request_type` is `[a-z0-9][a-z0-9_]{0,39}`: a lower-case key of at most 40 characters that does
|
||||
not start with `_` (an event identifier starts with a letter or digit).
|
||||
* `events.FIRST_EVENTS`: the comment on `workflow.approved` now names Workflow as its sender (it was
|
||||
"Compass (later Workflow)"). Comment only, no behaviour change.
|
||||
* Not here: the `workflow_app` grants in the event log — the hub adds it to `emitter_roles` in its
|
||||
event-grant revision before Workflow emits.
|
||||
### 0.25.0 notes
|
||||
|
||||
* `model_access.client.build_prompt`: a rule may carry `step_id`, `step_name`, `step_instruction`
|
||||
(a skill's step). Each new `step_id` gets a `## Krok: <name>` header, and the instruction under
|
||||
it, inside the rules fence. Rules without `step_id` ask byte for byte as before (golden test
|
||||
unchanged); `build_schema` ignores the extra keys. No schema change, no migration.
|
||||
|
||||
## Chat contract (0.26.0)
|
||||
|
||||
`dredd_core.chat_contract` (opt-in, standard library only, no tables) is K4 of the Compass split:
|
||||
what a module tells the platform's chat. The chat's rule is **code finds, the model reads**: the
|
||||
browser reads each module with the asker's own session, ranks one-sentence records against the
|
||||
question and gives the best ones to the model as numbered sources, with no tools. Instead of a
|
||||
hand-written reader per module in Atrium, a module may answer
|
||||
`GET <module>/api/v1/chat/records?offset=&limit=` with:
|
||||
|
||||
```json
|
||||
{"version": 1, "module": "galena", "as_of": "2026-11-25T10:00:00+00:00", "next_offset": null,
|
||||
"records": [{"key": "galena:umowa:1f0c", "kind": "umowa", "title": "UM-2026-0017 Najem biura",
|
||||
"text": "Umowa UM-2026-0017 „Najem biura”, kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
"link": "cards/1f0c", "labels": ["UM-2026-0017", "ACME"],
|
||||
"at": "2026-11-25T10:00:00+00:00"}]}
|
||||
```
|
||||
|
||||
* **Authorisation stays in the module**: a page holds only what the caller may read.
|
||||
* A record is one sentence about one thing: `key` (`<module>:<kind>:<id>`), `kind` (a lower-case
|
||||
word the chat may name), `title`, `text`, `link` (the search contract's link rule, so every cited
|
||||
source opens), optional `labels`, `at`, `members`. Bounded: 500 records a page, `next_offset`
|
||||
pages on (`null` on the last, and a page without the key is refused), title 300 and text 2000
|
||||
(both cut at a word with `…` by `make_record`), 10 labels of 200, 200 members of 300.
|
||||
* **Text is content and stays with the asker**: it goes to the asker's browser and the model they
|
||||
chose, nowhere else. Actions (a contract check, an approval run) are not records; the chat routes
|
||||
them in code.
|
||||
* Module side: `make_record`, `make_page(module, records, total=..., offset=...)` (both validate;
|
||||
`total` is required, so a module cannot forget it and end pagination after one page),
|
||||
`page_params` (clamped offset and limit),
|
||||
`validate_page` for conformance tests. The consumer is Atrium's console (JavaScript).
|
||||
|
||||
### 0.26.0 notes
|
||||
|
||||
* New, opt-in: `dredd_core.chat_contract`. No schema change, no migration.
|
||||
* `search_contract.link_ok` is public (the link rule every contract shares); `_link_ok` stays as an
|
||||
alias.
|
||||
|
||||
### 0.26.1 notes
|
||||
|
||||
* New: `schema.session_update_guard_sql(identity_schema, *, owner_role, writer_role)`, one `DO`
|
||||
block for the identity owner's revision, after `shared_identity_grants_sql`. It closes a gap the
|
||||
module tier's column grant left open: a module could un-revoke any session and extend any
|
||||
credential's expiry. Nothing changes for a module; the hub adds one revision. Standalone apps
|
||||
are not affected.
|
||||
|
||||
## What deliberately stays app-side
|
||||
|
||||
The HTTP edge (cookies, error handlers, request wiring), node-tree **CRUD** (it depends on the app's
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""The family's chat contract: ONE shape for what a module tells the platform's chat (K4).
|
||||
|
||||
Atrium's chat answers questions about the firm's data by the rule its measurements set (2026-10-28:
|
||||
9-10 of 10 answers right, against 2 of 10 when a model called the modules' APIs itself): **code
|
||||
finds, the model reads**. The browser reads every module the asker may read, with the asker's own
|
||||
session, turns each record into one sentence, ranks them against the question and hands the best
|
||||
ones to the model as numbered sources. Until now each module had a hand-written reader in Atrium
|
||||
(`chatSygna`, `chatCounsel`, `chatGalena` …); this contract lets a module say its records itself, in
|
||||
one shape, so the chat reads any module the same way:
|
||||
|
||||
GET <module>/api/v1/chat/records?offset=0&limit=500
|
||||
|
||||
answered with
|
||||
|
||||
{"version": 1, "module": "galena", "as_of": ISO-8601,
|
||||
"records": [Record, ...], "next_offset": int | null}
|
||||
|
||||
Rules of the contract, in order of importance:
|
||||
|
||||
1. **Authorisation stays in the module.** A page holds only records the CALLER may read, by the
|
||||
same checks the module's own screens make. The chat never filters or re-checks; it reads what it
|
||||
is given, with the person's session (`credentials: same-origin`), never a service account.
|
||||
2. **A record is one sentence about one thing**, written by the module in its own language:
|
||||
``{"key", "kind", "title", "text", "link"}`` plus optional ``"labels"`` (names a question may
|
||||
use for it: a number, a counterparty, a case signature), ``"at"`` (ISO-8601, when it happened or
|
||||
was last changed) and ``"members"`` (keys of records it groups, for a summary record).
|
||||
``key`` is ``<module>:<kind>:<id>`` and unique in the module; ``kind`` is a lower-case word the
|
||||
chat may name (``umowa``, ``sprawa``, ``termin``); ``link`` is a route in the module's console,
|
||||
relative to its root (the search contract's link rule: ``"cards/<id>"``, opened as
|
||||
``<module root>#/cards/<id>``), so every source the model cites can be opened and checked.
|
||||
3. **Text is content, and stays with the asker.** Unlike stats and events, a record carries names,
|
||||
titles and figures: what the person could read on the screen anyway. It travels to the asker's
|
||||
browser and from there to the model the asker chose; a module never sends it anywhere else, and
|
||||
the chat neither stores nor forwards it beyond that conversation.
|
||||
4. **Bounded.** At most :data:`MAX_RECORDS` records a page; a longer list pages through
|
||||
``next_offset`` (``null`` on the last page). ``title`` ≤ :data:`MAX_TITLE`, ``text`` ≤
|
||||
:data:`MAX_TEXT` characters, at most :data:`MAX_LABELS` labels and :data:`MAX_MEMBERS` members.
|
||||
|
||||
Actions (ordering a contract check, starting an approval run) are NOT records: the chat routes them
|
||||
in code, module by module. Extra top-level keys are allowed and ignored (a module may grow); extra
|
||||
record keys are not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
from .search_contract import link_ok
|
||||
|
||||
__all__ = [
|
||||
"VERSION",
|
||||
"PATH",
|
||||
"MAX_RECORDS",
|
||||
"MAX_TITLE",
|
||||
"MAX_TEXT",
|
||||
"MAX_LABELS",
|
||||
"MAX_LABEL",
|
||||
"MAX_MEMBERS",
|
||||
"MAX_MEMBER",
|
||||
"Record",
|
||||
"RecordsPage",
|
||||
"ContractError",
|
||||
"make_record",
|
||||
"make_page",
|
||||
"page_params",
|
||||
"validate_record",
|
||||
"validate_page",
|
||||
]
|
||||
|
||||
VERSION = 1
|
||||
#: The path every module answers, under its ``/api/v1``.
|
||||
PATH = "/chat/records"
|
||||
MAX_RECORDS = 500
|
||||
MAX_TITLE = 300
|
||||
MAX_TEXT = 2000
|
||||
MAX_LABELS = 10
|
||||
MAX_LABEL = 200
|
||||
MAX_MEMBERS = 200
|
||||
#: The longest member key (a record key: module, kind and id with their separators).
|
||||
MAX_MEMBER = 300
|
||||
|
||||
#: The family's module slug, as `module_permission.module_slug` holds it: hyphens, never underscores.
|
||||
_MODULE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||||
_KIND = re.compile(r"^[a-ząćęłńóśźż][a-ząćęłńóśźż0-9_]{0,39}$")
|
||||
_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
||||
_FIELDS = frozenset({"key", "kind", "title", "text", "link", "labels", "at", "members"})
|
||||
|
||||
|
||||
class Record(TypedDict):
|
||||
key: str
|
||||
kind: str
|
||||
title: str
|
||||
text: str
|
||||
link: str
|
||||
labels: NotRequired[list[str]]
|
||||
at: NotRequired[str]
|
||||
members: NotRequired[list[str]]
|
||||
|
||||
|
||||
class RecordsPage(TypedDict):
|
||||
version: int
|
||||
module: str
|
||||
as_of: str
|
||||
records: list[Record]
|
||||
next_offset: int | None
|
||||
|
||||
|
||||
class ContractError(ValueError):
|
||||
"""A page or record that does not conform to the contract."""
|
||||
|
||||
|
||||
def _iso(value: Any) -> str:
|
||||
if value is None:
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
||||
if isinstance(value, dt.datetime):
|
||||
if value.tzinfo is None:
|
||||
raise ContractError("a time must carry its timezone")
|
||||
return value.isoformat(timespec="seconds")
|
||||
if isinstance(value, dt.date):
|
||||
return value.isoformat()
|
||||
return str(value)
|
||||
|
||||
|
||||
def _is_iso(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
try:
|
||||
dt.datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _one_line(value: str) -> str:
|
||||
return re.sub(r"\s+", " ", value).strip()
|
||||
|
||||
|
||||
def _cut(value: str, most: int) -> str:
|
||||
"""`value` folded to one line and, when longer than `most`, cut at a word with an ellipsis."""
|
||||
value = _one_line(value)
|
||||
if len(value) > most:
|
||||
value = value[:most - 1].rsplit(" ", 1)[0] + "…"
|
||||
return value
|
||||
|
||||
|
||||
def make_record(*, module: str, kind: str, id: Any, title: str, text: str, link: str, # noqa: A002
|
||||
labels: Iterable[str] = (), at: Any = None,
|
||||
members: Iterable[str] = ()) -> Record:
|
||||
"""One record, its key built as ``<module>:<kind>:<id>``, whitespace folded, validated.
|
||||
A title longer than :data:`MAX_TITLE` and text longer than :data:`MAX_TEXT` are cut at a word
|
||||
with an ellipsis rather than refused: a long note is still a record, and the chat reads its
|
||||
beginning. Labels and members are folded the same way and blank ones dropped; one over its
|
||||
length limit is refused (a cut label or key would no longer name anything)."""
|
||||
record: Record = {"key": f"{module}:{kind}:{id}", "kind": kind,
|
||||
"title": _cut(title, MAX_TITLE), "text": _cut(text, MAX_TEXT), "link": link}
|
||||
labels = [_one_line(x) for x in labels if x and _one_line(x)]
|
||||
if labels:
|
||||
record["labels"] = labels
|
||||
if at is not None:
|
||||
record["at"] = _iso(at)
|
||||
members = [_one_line(x) for x in members if x and _one_line(x)]
|
||||
if members:
|
||||
record["members"] = members
|
||||
validate_record(record, module=module)
|
||||
return record
|
||||
|
||||
|
||||
def make_page(module: str, records: list[Record], *, total: int, offset: int = 0,
|
||||
as_of: Any = None) -> RecordsPage:
|
||||
"""The response for one page: ``next_offset`` is ``offset + len(records)`` while `total` (how
|
||||
many records the caller may read in all) says more remain, ``None`` once this page reaches it.
|
||||
`total` is required, so a module cannot leave it out and silently end pagination after the
|
||||
first page. Validated."""
|
||||
more = offset + len(records) < total
|
||||
page: RecordsPage = {"version": VERSION, "module": module, "as_of": _iso(as_of),
|
||||
"records": records,
|
||||
"next_offset": offset + len(records) if more and records else None}
|
||||
validate_page(page)
|
||||
return page
|
||||
|
||||
|
||||
def page_params(offset: Any = 0, limit: Any = MAX_RECORDS) -> tuple[int, int]:
|
||||
"""The request's ``offset`` and ``limit`` as a module should read them: integers, ``offset`` ≥ 0,
|
||||
``limit`` within 1..:data:`MAX_RECORDS` (clamped, not refused)."""
|
||||
try:
|
||||
off = max(0, int(offset))
|
||||
except (TypeError, ValueError):
|
||||
off = 0
|
||||
try:
|
||||
lim = min(MAX_RECORDS, max(1, int(limit)))
|
||||
except (TypeError, ValueError):
|
||||
lim = MAX_RECORDS
|
||||
return off, lim
|
||||
|
||||
|
||||
def _strings(record: Mapping[str, Any], field: str, most: int, longest: int) -> None:
|
||||
value = record.get(field)
|
||||
if value is None:
|
||||
return
|
||||
if not isinstance(value, list) or not all(isinstance(x, str) and x for x in value):
|
||||
raise ContractError(f"record.{field} is not a list of non-empty strings")
|
||||
if len(value) > most:
|
||||
raise ContractError(f"record.{field} has {len(value)} items, over {most}")
|
||||
if any(len(x) > longest for x in value):
|
||||
raise ContractError(f"record.{field} has an item over {longest} characters")
|
||||
|
||||
|
||||
def validate_record(record: Any, *, module: str | None = None) -> None:
|
||||
"""Raise :class:`ContractError` unless `record` conforms; with `module`, its key must be that
|
||||
module's."""
|
||||
if not isinstance(record, dict):
|
||||
raise ContractError("record is not an object")
|
||||
extra = set(record) - _FIELDS
|
||||
if extra:
|
||||
raise ContractError(f"record has keys outside the contract: {sorted(extra)}")
|
||||
for field in ("key", "kind", "title", "text", "link"):
|
||||
if not isinstance(record.get(field), str):
|
||||
raise ContractError(f"record.{field} missing or not a string")
|
||||
kind = record["kind"]
|
||||
if not _KIND.match(kind):
|
||||
raise ContractError(f"record.kind is not a lower-case word: {kind!r}")
|
||||
parts = record["key"].split(":", 2)
|
||||
if (len(parts) != 3 or not _MODULE.match(parts[0]) or parts[1] != kind
|
||||
or not _ID.match(parts[2])):
|
||||
raise ContractError(f"record.key is not <module>:<kind>:<id>: {record['key']!r}")
|
||||
if module is not None and parts[0] != module:
|
||||
raise ContractError(f"record.key names module {parts[0]!r}, not {module!r}")
|
||||
if not record["title"].strip() or len(record["title"]) > MAX_TITLE:
|
||||
raise ContractError(f"record.title is empty or over {MAX_TITLE} characters")
|
||||
if not record["text"].strip() or len(record["text"]) > MAX_TEXT:
|
||||
raise ContractError(f"record.text is empty or over {MAX_TEXT} characters")
|
||||
if not link_ok(record["link"]):
|
||||
raise ContractError(f"record.link is not a console route: {record['link']!r}")
|
||||
_strings(record, "labels", MAX_LABELS, MAX_LABEL)
|
||||
_strings(record, "members", MAX_MEMBERS, MAX_MEMBER)
|
||||
if "at" in record and not _is_iso(record["at"]):
|
||||
raise ContractError("record.at is not an ISO-8601 string")
|
||||
|
||||
|
||||
def validate_page(body: Any) -> None:
|
||||
"""Raise :class:`ContractError` unless `body` conforms (extra top-level keys are allowed)."""
|
||||
if not isinstance(body, dict):
|
||||
raise ContractError("page is not an object")
|
||||
if body.get("version") != VERSION:
|
||||
raise ContractError(f"page.version is not {VERSION}: {body.get('version')!r}")
|
||||
module = body.get("module")
|
||||
if not isinstance(module, str) or not _MODULE.match(module):
|
||||
raise ContractError(f"page.module is not a module slug: {module!r}")
|
||||
if not _is_iso(body.get("as_of")):
|
||||
raise ContractError("page.as_of missing or not an ISO-8601 string")
|
||||
records = body.get("records")
|
||||
if not isinstance(records, list):
|
||||
raise ContractError("page.records missing or not a list")
|
||||
if len(records) > MAX_RECORDS:
|
||||
raise ContractError(f"page carries {len(records)} records, over {MAX_RECORDS}")
|
||||
if "next_offset" not in body:
|
||||
raise ContractError("page.next_offset is missing (it is null on the last page)")
|
||||
nxt = body["next_offset"]
|
||||
if nxt is not None and (isinstance(nxt, bool) or not isinstance(nxt, int) or nxt < 1):
|
||||
raise ContractError("page.next_offset is neither null nor a positive integer")
|
||||
seen: set[str] = set()
|
||||
for record in records:
|
||||
validate_record(record, module=module)
|
||||
if record["key"] in seen:
|
||||
raise ContractError(f"record key {record['key']!r} appears twice")
|
||||
seen.add(record["key"])
|
||||
@@ -143,7 +143,7 @@ _MAX_INT = 2 ** 53
|
||||
#: The first events of the plan. Documentation, not an allowlist: a new kind needs no core release.
|
||||
FIRST_EVENTS: tuple[str, ...] = (
|
||||
"document.version_added", # Galena: a commit on a document (published or a working version)
|
||||
"workflow.approved", # Compass (later Workflow): the last stage of an approval passed
|
||||
"workflow.approved", # Workflow: the last stage of an approval passed
|
||||
"document.signed", # Parafa: the signed file is back
|
||||
"negotiation.round_received", # Agora: the other side's round arrived
|
||||
"analysis.accepted", # Arbiter: a lawyer accepted the analysis (a frozen card on offer)
|
||||
|
||||
@@ -894,8 +894,8 @@ def _model_provider_rules(role_tier: str, keys: bool) -> dict[str, _IdentityRule
|
||||
}
|
||||
if role_tier == "writer":
|
||||
return {
|
||||
"model_provider": _IdentityRule(required=("SELECT", "INSERT", "UPDATE"),
|
||||
forbidden=("DELETE", "TRUNCATE")),
|
||||
"model_provider": _IdentityRule(required=("SELECT", "INSERT", "UPDATE", "DELETE"),
|
||||
forbidden=("TRUNCATE",)),
|
||||
"model_provider_policy": _IdentityRule(required=("SELECT", "INSERT", "UPDATE"),
|
||||
forbidden=("DELETE", "TRUNCATE")),
|
||||
MODEL_PROVIDER_KEY_TABLE: _IdentityRule(
|
||||
|
||||
@@ -271,7 +271,7 @@ def build_prompt(
|
||||
section as material to judge.
|
||||
"""
|
||||
clause_lines = "\n".join(f"[{c['id']}] {c['label']}: {c['text']}" for c in clauses)
|
||||
rule_lines = "\n".join(_rule_line(r) for r in rules)
|
||||
rule_lines = _rule_block(rules)
|
||||
# A rule with a standard (spec 2026-10-13 rejestr-klauzule, BK7) says what `spelnia` means
|
||||
# for it. Added only then, so a version without standards asks byte for byte as before.
|
||||
task = TASK + (STANDARD_TASK if any(r.get("standard") or r.get("fallback") for r in rules)
|
||||
@@ -290,6 +290,28 @@ def build_prompt(
|
||||
)
|
||||
|
||||
|
||||
def _rule_block(rules: Sequence[Mapping[str, Any]]) -> str:
|
||||
"""The rule lines, each new `step_id` headed by its step's name and instruction.
|
||||
|
||||
A rule from a skill carries the step it came from (`step_id`, `step_name`, `step_instruction`).
|
||||
The header sits inside the rules fence, so the lawyer's instruction is read as an order and
|
||||
never leaks into the contract or task sections. Rules without a `step_id` add no header,
|
||||
which keeps a version without steps asking byte for byte as before.
|
||||
"""
|
||||
lines: list[str] = []
|
||||
current = None
|
||||
for rule in rules:
|
||||
step_id = rule.get("step_id")
|
||||
if step_id and step_id != current:
|
||||
lines.append(f"## Krok: {rule.get('step_name') or step_id}")
|
||||
if rule.get("step_instruction"):
|
||||
lines.append(rule["step_instruction"])
|
||||
if step_id:
|
||||
current = step_id
|
||||
lines.append(_rule_line(rule))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _rule_line(rule: Mapping[str, Any]) -> str:
|
||||
line = f"[{rule['id']}] {rule['text']}"
|
||||
if rule.get("standard"):
|
||||
|
||||
@@ -22,7 +22,7 @@ block:
|
||||
role ``model_provider`` ``model_provider_policy`` ``model_provider_key``
|
||||
========================= ================ ===================== ======================
|
||||
`writer_role` (the hub) SELECT, INSERT, SELECT, INSERT, SELECT, INSERT,
|
||||
UPDATE UPDATE UPDATE, DELETE
|
||||
UPDATE, DELETE UPDATE UPDATE, DELETE
|
||||
`reader_roles` (modules) SELECT SELECT **nothing**
|
||||
`key_reader_roles` SELECT SELECT SELECT
|
||||
`migrator_roles` SELECT, nothing nothing
|
||||
@@ -118,7 +118,7 @@ provider only on this machine.
|
||||
Audit
|
||||
-----
|
||||
Every write is in the writer's own audit log through :func:`dredd_core.audit.record`:
|
||||
``model_provider.create`` / ``.update`` / ``.disable`` (``entity_id`` = the provider, ``detail`` = its
|
||||
``model_provider.create`` / ``.update`` / ``.disable`` / ``.delete`` (``entity_id`` = the provider, ``detail`` = its
|
||||
name, ``diff`` = what changed) and ``model_provider.policy``. A key is never in a diff — only that it
|
||||
was set or cleared.
|
||||
|
||||
@@ -157,12 +157,13 @@ from sqlalchemy import (
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from . import audit
|
||||
from .base import Base, TimestampMixin, UUIDPkMixin
|
||||
from .errors import AppError, NotFoundError, ValidationError
|
||||
from .errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from .identity import (
|
||||
MODEL_PROVIDER_KEY_TABLE,
|
||||
MODEL_PROVIDER_TABLES,
|
||||
@@ -199,6 +200,7 @@ __all__ = [
|
||||
"clear_user_key",
|
||||
"create",
|
||||
"create_model_provider_tables",
|
||||
"delete_unused",
|
||||
"disable",
|
||||
"drop_model_provider_import_sql",
|
||||
"eu_only",
|
||||
@@ -341,6 +343,17 @@ MESSAGES: Mapping[str, tuple[str, str]] = MappingProxyType({
|
||||
"key_mode_unknown": (
|
||||
"Źródło klucza to jedno z: $modes.",
|
||||
"The key source is one of: $modes."),
|
||||
"provider_still_active": (
|
||||
"Najpierw wyłącz dostawcę, potem go usuń.",
|
||||
"Disable the provider first, then delete it."),
|
||||
"provider_reference_unsafe": (
|
||||
"Tabela $tables wskazuje na dostawcę bez RESTRICT, więc usunięcie skasowałoby albo wyczyściło "
|
||||
"jej przebiegi. Dostawcę można tylko wyłączyć.",
|
||||
"Table $tables points at the provider without RESTRICT, so deleting it would erase or blank "
|
||||
"its runs. The provider can only be disabled."),
|
||||
"provider_in_use": (
|
||||
"Ten dostawca policzył już przebiegi, więc można go tylko wyłączyć.",
|
||||
"This provider has already computed runs, so it can only be disabled."),
|
||||
})
|
||||
#: The codes of :data:`MESSAGES`, for an app's test that its console covers every one of them.
|
||||
MESSAGE_CODES: frozenset[str] = frozenset(MESSAGES)
|
||||
@@ -383,7 +396,8 @@ class ModelProvider(UUIDPkMixin, TimestampMixin, Base):
|
||||
ForeignKey("app_user.id", ondelete="RESTRICT"))
|
||||
# Narrows the platform's level for this one provider; NULL = whatever the policy says.
|
||||
allowed_for: Mapped[str | None] = mapped_column(String(20))
|
||||
# Disabling, never deleting: a run records which provider computed it.
|
||||
# Disabling is the default way out: a run records which provider computed it, so only a
|
||||
# provider no run points at may be deleted (`delete_unused`).
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
# The first characters of the key, not secret: lets a screen in ANY module say "a key is set,
|
||||
# it starts sk-abc" without the key opt-in. NULL = no key.
|
||||
@@ -903,7 +917,7 @@ def update(db: DbSession, *, actor: Any, provider: ModelProvider, name: str | No
|
||||
|
||||
def disable(db: DbSession, *, actor: Any, provider: ModelProvider,
|
||||
ip: str | None = None) -> ModelProvider:
|
||||
"""Switched off, never deleted: a finished run records which provider computed it."""
|
||||
"""Switched off, the row kept: a finished run records which provider computed it."""
|
||||
if provider.is_active:
|
||||
provider.is_active = False
|
||||
db.flush()
|
||||
@@ -911,6 +925,68 @@ def disable(db: DbSession, *, actor: Any, provider: ModelProvider,
|
||||
return provider
|
||||
|
||||
|
||||
_FOREIGN_KEY_VIOLATION = "23503"
|
||||
|
||||
|
||||
def _sqlstate(exc: DBAPIError) -> str | None:
|
||||
"""The server's SQLSTATE, whichever driver raised. Matched on the code, not the exception class:
|
||||
pg8000 maps only 23505 to ``IntegrityError`` and a foreign-key violation to ``ProgrammingError``."""
|
||||
orig = exc.orig
|
||||
code = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None) # psycopg 3 / psycopg2
|
||||
if code is None and orig is not None and orig.args and isinstance(orig.args[0], dict):
|
||||
code = orig.args[0].get("C") # pg8000
|
||||
return code
|
||||
|
||||
|
||||
def _unsafe_references(db: DbSession, provider_id: uuid.UUID) -> list[str]:
|
||||
"""Foreign keys to ``model_provider`` whose ON DELETE is neither RESTRICT nor NO ACTION, core's
|
||||
own key tables (CASCADE by design: a key goes with its provider) left out. The table's oid comes
|
||||
off the row itself, so it is the table this session actually writes, whatever the search_path."""
|
||||
rel = db.scalar(select(text("tableoid")).select_from(ModelProvider)
|
||||
.where(ModelProvider.id == provider_id))
|
||||
rows = db.execute(text(
|
||||
"SELECT c.conrelid::regclass::text FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid "
|
||||
"WHERE c.contype = 'f' AND c.confrelid = :rel AND c.confdeltype NOT IN ('r', 'a') "
|
||||
"AND NOT (t.relnamespace = (SELECT relnamespace FROM pg_class WHERE oid = :rel) "
|
||||
"AND t.relname IN (:key, :user_key)) ORDER BY 1"),
|
||||
{"rel": rel, "key": MODEL_PROVIDER_KEY_TABLE, "user_key": MODEL_PROVIDER_USER_KEY_TABLE})
|
||||
return [name for (name,) in rows]
|
||||
|
||||
|
||||
def delete_unused(db: DbSession, *, actor: Any, provider: ModelProvider,
|
||||
ip: str | None = None) -> None:
|
||||
"""Deletes a disabled provider no run points at, its stored keys (firm and personal) with it.
|
||||
|
||||
The way out for a provider that never computed anything — a key that expired after a day, a
|
||||
test entry, a typo. Refused while it is active (``provider_still_active``, 409): a module may be
|
||||
offering it this minute. Refused once any run points at it (``provider_in_use``, 409), and core
|
||||
does not list who may point: every module's foreign key to ``model_provider`` is ``RESTRICT``
|
||||
(the migrator tier's ``REFERENCES``), so the database answers for modules core has never heard
|
||||
of. The attempt runs in a savepoint, so a refusal leaves the caller's transaction usable.
|
||||
Audited as ``model_provider.delete`` with the name in ``detail``: the audit row outlives the
|
||||
provider it names.
|
||||
|
||||
The RESTRICT is checked, not assumed: a foreign key from outside core's own key tables that would
|
||||
cascade or null on delete refuses the delete (``provider_reference_unsafe``, 409) before it runs,
|
||||
so a module that got its key wrong loses nothing."""
|
||||
if provider.is_active:
|
||||
raise _refuse("provider_still_active", ConflictError)
|
||||
unsafe = _unsafe_references(db, provider.id)
|
||||
if unsafe:
|
||||
raise _refuse("provider_reference_unsafe", ConflictError, tables=", ".join(unsafe))
|
||||
provider_id, name = provider.id, provider.name
|
||||
try:
|
||||
with db.begin_nested():
|
||||
db.delete(provider)
|
||||
db.flush()
|
||||
except DBAPIError as exc:
|
||||
if _sqlstate(exc) != _FOREIGN_KEY_VIOLATION:
|
||||
raise
|
||||
raise _refuse("provider_in_use", ConflictError) from None
|
||||
audit.record(db, actor_id=getattr(actor, "id", None), action="model_provider.delete",
|
||||
entity_type="model_provider", entity_id=provider_id, detail=name, ip=ip)
|
||||
|
||||
|
||||
# ── personal keys (the hub) ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1187,9 +1263,10 @@ BEGIN
|
||||
END LOOP;
|
||||
END LOOP;
|
||||
|
||||
-- The hub: writes the list and the policy, never deletes a provider (disable it), and manages
|
||||
-- keys outright (clearing a key is a DELETE of its row).
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE ON TABLE ' || qs || '.model_provider TO ' || quote_ident(writer_role);
|
||||
-- The hub: writes the list and the policy, deletes a provider only when no run points at it
|
||||
-- (every module's foreign key is RESTRICT, so the database refuses the rest), and manages keys
|
||||
-- outright (clearing a key is a DELETE of its row).
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ' || qs || '.model_provider TO ' || quote_ident(writer_role);
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE ON TABLE ' || qs || '.model_provider_policy TO ' || quote_ident(writer_role);
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ' || qs || '.model_provider_key TO ' || quote_ident(writer_role);
|
||||
-- Personal keys: the hub's alone. No reader, opted in or not, and no migrator gets anything.
|
||||
@@ -1209,6 +1286,7 @@ BEGIN
|
||||
IF NOT (has_table_privilege(writer_role, provider_rel, 'SELECT')
|
||||
AND has_table_privilege(writer_role, provider_rel, 'INSERT')
|
||||
AND has_table_privilege(writer_role, provider_rel, 'UPDATE')
|
||||
AND has_table_privilege(writer_role, provider_rel, 'DELETE')
|
||||
AND has_table_privilege(writer_role, policy_rel, 'SELECT')
|
||||
AND has_table_privilege(writer_role, policy_rel, 'INSERT')
|
||||
AND has_table_privilege(writer_role, policy_rel, 'UPDATE')
|
||||
|
||||
@@ -372,6 +372,56 @@ def account_delete_guard_sql(identity_schema: str, *, owner_role: str,
|
||||
)
|
||||
|
||||
|
||||
def session_update_guard_sql(identity_schema: str, *, owner_role: str, writer_role: str,
|
||||
session_table: str = "session") -> str:
|
||||
"""One idempotent statement that keeps a module from reviving or prolonging a credential.
|
||||
|
||||
:func:`shared_identity_grants_sql` gives every reader ``UPDATE`` on three ``session`` columns
|
||||
(:data:`~dredd_core.identity.SESSION_UPDATE_COLUMNS`), because ``resolve_session_full`` writes
|
||||
``last_seen_at`` and slides an app token's ``expires_at``, and signing out of a module writes
|
||||
``revoked_at``. A column grant cannot say *which values* may be written, and it covers every row,
|
||||
so without this guard any one module role (compromised, or reached through SQL injection) could
|
||||
set ``revoked_at = NULL`` on a session the hub revoked, or push ``expires_at`` to ``infinity`` on
|
||||
the administrator's session. Revocation would then be a kill-switch against everyone except the
|
||||
modules, which are the place a stolen cookie is most likely to be seen.
|
||||
|
||||
A row-level ``BEFORE UPDATE`` trigger on ``<identity_schema>.session`` therefore refuses, for
|
||||
every role except `owner_role` and `writer_role` (the hub):
|
||||
|
||||
* a change to any column other than those three (defence in depth behind the column grant);
|
||||
* any change to ``revoked_at`` once it is set: a revoked credential stays revoked;
|
||||
* any later ``expires_at``, except the one slide core itself makes: an app token that is live
|
||||
(not revoked, not expired) moving to at most ``idle_days`` from now. An interactive session
|
||||
never slides, so a module may never extend one.
|
||||
|
||||
Setting ``revoked_at`` on a live row, moving ``last_seen_at``, and shortening ``expires_at`` stay
|
||||
open, so a module's sign-out and session resolution keep working unchanged. Both time checks
|
||||
allow one hour for the clock of the app host differing from the database's.
|
||||
|
||||
Run it from the identity owner's revision, after :func:`shared_identity_grants_sql`. The trigger
|
||||
function is not ``SECURITY DEFINER`` (it decides on ``current_user``, the role that issued the
|
||||
UPDATE) and pins ``search_path = pg_catalog, pg_temp``. Only the table's owner can disable it,
|
||||
and ``session_replication_role`` is a superuser setting.
|
||||
"""
|
||||
schema = _sql_name(identity_schema, "identity_schema")
|
||||
owner = _sql_name(owner_role, "owner_role")
|
||||
writer = _sql_name(writer_role, "writer_role")
|
||||
sessions = _sql_name(session_table, "session_table")
|
||||
for what, name in (("identity_schema", schema), ("owner_role", owner),
|
||||
("writer_role", writer), ("session_table", sessions)):
|
||||
if "$" in name: # it is rendered into a dollar-quoted body, which a `$` could close
|
||||
raise ValueError(f"{what}: {name!r} must not contain '$'")
|
||||
if owner == writer:
|
||||
raise ValueError("owner_role and writer_role must be different roles")
|
||||
return _SESSION_UPDATE_GUARD_TEMPLATE.format(
|
||||
identity_schema=_sql_literal(schema),
|
||||
owner_role=_sql_literal(owner),
|
||||
writer_role=_sql_literal(writer),
|
||||
session_table=_sql_literal(sessions),
|
||||
admin_roles=", ".join(_sql_literal(name) for name in _ADMIN_ROLE_NAMES),
|
||||
)
|
||||
|
||||
|
||||
def _sql_name(value: str, what: str) -> str:
|
||||
if not isinstance(value, str) or not _SQL_NAME.match(value):
|
||||
raise ValueError(f"{what}: {value!r} is not a plain SQL identifier")
|
||||
@@ -984,3 +1034,89 @@ BEGIN
|
||||
END IF;
|
||||
END
|
||||
$dredd_account_delete_guard$"""
|
||||
|
||||
|
||||
# Built like the delete guard: the function body ($dredd_guard_session_update$) and every literal in
|
||||
# it ($dredd_k$ / $dredd_msg$ / $dredd_hint$) are dollar-quoted, so the CREATE sits inside one
|
||||
# EXECUTE '...' with no quote doubling. The two role names are the only values spliced in, through
|
||||
# quote_literal at run time (and `session_update_guard_sql` refuses a `$` in any name). No "%" and no
|
||||
# ":name" anywhere, for the same reason as every other block in this module.
|
||||
_SESSION_UPDATE_GUARD_TEMPLATE = """\
|
||||
DO $dredd_session_update_guard$
|
||||
DECLARE
|
||||
sch text := {identity_schema};
|
||||
owner_role text := {owner_role};
|
||||
writer_role text := {writer_role};
|
||||
session_table text := {session_table};
|
||||
qs text;
|
||||
qt text;
|
||||
BEGIN
|
||||
IF current_user::text <> owner_role THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'session update guard: connected as ' || quote_ident(current_user::text)
|
||||
|| ', not the identity owner ' || quote_ident(owner_role),
|
||||
HINT = 'Run this from the identity owner''s own migration, after the identity grants.';
|
||||
END IF;
|
||||
IF (SELECT rolsuper FROM pg_roles WHERE rolname = owner_role)
|
||||
OR owner_role IN ({admin_roles}) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'session update guard: the identity owner ' || quote_ident(owner_role)
|
||||
|| ' is a superuser or the platform admin role',
|
||||
HINT = 'Identity is owned by an ordinary migrator role.';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = writer_role) THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'session update guard: the writer role ' || quote_ident(writer_role)
|
||||
|| ' does not exist',
|
||||
HINT = 'Pass the hub''s runtime role, the same writer_role as the identity grants.';
|
||||
END IF;
|
||||
qs := quote_ident(sch);
|
||||
qt := qs || '.' || quote_ident(session_table);
|
||||
IF to_regclass(qt) IS NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'session update guard: table ' || qt || ' does not exist',
|
||||
HINT = 'Create the shared identity tables in this revision, before the guard.';
|
||||
END IF;
|
||||
|
||||
EXECUTE 'CREATE OR REPLACE FUNCTION ' || qs || '.guard_session_update() RETURNS trigger '
|
||||
|| 'LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp '
|
||||
|| 'AS $dredd_guard_session_update$ BEGIN '
|
||||
|| 'IF current_user::text IN (' || quote_literal(owner_role) || ', '
|
||||
|| quote_literal(writer_role) || ') THEN RETURN NEW; END IF; '
|
||||
|| 'IF (to_jsonb(NEW) - ARRAY[$dredd_k$last_seen_at$dredd_k$, $dredd_k$expires_at$dredd_k$, '
|
||||
|| '$dredd_k$revoked_at$dredd_k$]::text[]) IS DISTINCT FROM (to_jsonb(OLD) - '
|
||||
|| 'ARRAY[$dredd_k$last_seen_at$dredd_k$, $dredd_k$expires_at$dredd_k$, '
|
||||
|| '$dredd_k$revoked_at$dredd_k$]::text[]) THEN RAISE EXCEPTION USING '
|
||||
|| 'MESSAGE = $dredd_msg$session update guard: a module writes only last_seen_at, expires_at and revoked_at$dredd_msg$, '
|
||||
|| 'HINT = $dredd_hint$Accounts and credentials are the hub''s to write.$dredd_hint$; '
|
||||
|| 'END IF; '
|
||||
|| 'IF OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at THEN '
|
||||
|| 'RAISE EXCEPTION USING '
|
||||
|| 'MESSAGE = $dredd_msg$session update guard: a revoked credential stays revoked$dredd_msg$, '
|
||||
|| 'HINT = $dredd_hint$Only the hub may change a revoked session or app token.$dredd_hint$; '
|
||||
|| 'END IF; '
|
||||
|| 'IF NEW.expires_at > OLD.expires_at AND ('
|
||||
|| 'OLD.kind IS DISTINCT FROM $dredd_k$app_token$dredd_k$ OR OLD.idle_days IS NULL '
|
||||
|| 'OR OLD.revoked_at IS NOT NULL OR NEW.revoked_at IS NOT NULL '
|
||||
|| 'OR OLD.expires_at <= clock_timestamp() - make_interval(hours => 1) '
|
||||
|| 'OR NEW.expires_at > clock_timestamp() + make_interval(days => OLD.idle_days, hours => 1)'
|
||||
|| ') THEN RAISE EXCEPTION USING '
|
||||
|| 'MESSAGE = $dredd_msg$session update guard: only the hub extends a credential$dredd_msg$, '
|
||||
|| 'HINT = $dredd_hint$A module may slide a live app token to at most idle_days from now, '
|
||||
|| 'and nothing else.$dredd_hint$; '
|
||||
|| 'END IF; '
|
||||
|| 'RETURN NEW; END $dredd_guard_session_update$';
|
||||
EXECUTE 'REVOKE ALL ON FUNCTION ' || qs || '.guard_session_update() FROM PUBLIC';
|
||||
EXECUTE 'DROP TRIGGER IF EXISTS guard_session_update ON ' || qt;
|
||||
EXECUTE 'CREATE TRIGGER guard_session_update BEFORE UPDATE ON ' || qt
|
||||
|| ' FOR EACH ROW EXECUTE FUNCTION ' || qs || '.guard_session_update()';
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger
|
||||
WHERE tgrelid = to_regclass(qt) AND tgname = 'guard_session_update'
|
||||
AND NOT tgisinternal AND tgenabled <> 'D') THEN
|
||||
RAISE EXCEPTION USING
|
||||
MESSAGE = 'session update guard: the trigger on ' || qt || ' was not created',
|
||||
HINT = 'Only the owner of the table can put a trigger on it.';
|
||||
END IF;
|
||||
END
|
||||
$dredd_session_update_guard$"""
|
||||
|
||||
@@ -59,6 +59,7 @@ __all__ = [
|
||||
"validate_hit",
|
||||
"validate_response",
|
||||
"ContractError",
|
||||
"link_ok",
|
||||
]
|
||||
|
||||
VERSION = 1
|
||||
@@ -153,7 +154,9 @@ def empty_response(q: str = "") -> SearchResponse:
|
||||
return {"version": VERSION, "q": q, "hits": [], "truncated": False}
|
||||
|
||||
|
||||
def _link_ok(link: Any) -> bool:
|
||||
def link_ok(link: Any) -> bool:
|
||||
"""True for a console route relative to the module root (``"cards/<id>"``): not absolute, not a
|
||||
fragment, no scheme. The rule every contract's ``link`` follows."""
|
||||
if not isinstance(link, str) or not link.strip():
|
||||
return False
|
||||
if link.startswith(("/", "#")) or "://" in link or link.lower().startswith("javascript:"):
|
||||
@@ -161,6 +164,10 @@ def _link_ok(link: Any) -> bool:
|
||||
return "undefined" not in link and "null" not in link.split("/") and "None" not in link.split("/")
|
||||
|
||||
|
||||
#: Kept for modules that imported the private name before :func:`link_ok` was public.
|
||||
_link_ok = link_ok
|
||||
|
||||
|
||||
def validate_hit(hit: Any) -> None:
|
||||
if not isinstance(hit, dict):
|
||||
raise ContractError(f"hit is not an object: {hit!r}")
|
||||
@@ -173,7 +180,7 @@ def validate_hit(hit: Any) -> None:
|
||||
raise ContractError(f"hit.title is empty: {hit!r}")
|
||||
if not hit["id"]:
|
||||
raise ContractError(f"hit.id is empty: {hit!r}")
|
||||
if not _link_ok(hit["link"]):
|
||||
if not link_ok(hit["link"]):
|
||||
raise ContractError(f"hit.link is not a module-relative route: {hit['link']!r}")
|
||||
if "kind_label" in hit and not isinstance(hit["kind_label"], str):
|
||||
raise ContractError("hit.kind_label is not a string")
|
||||
|
||||
@@ -43,7 +43,7 @@ from collections.abc import Callable, Iterable, Mapping
|
||||
from concurrent.futures import ThreadPoolExecutor, wait
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
from .search_contract import _link_ok
|
||||
from .search_contract import link_ok
|
||||
|
||||
__all__ = [
|
||||
"VERSION",
|
||||
@@ -162,7 +162,7 @@ def validate_tile(tile: Any) -> None:
|
||||
count = tile.get("count")
|
||||
if isinstance(count, bool) or not isinstance(count, int) or not 0 <= count <= MAX_COUNT:
|
||||
raise ContractError(f"tile.count is not a non-negative integer: {count!r}")
|
||||
if not _link_ok(tile["link"]):
|
||||
if not link_ok(tile["link"]):
|
||||
raise ContractError(f"tile.link is not a module-relative route: {tile['link']!r}")
|
||||
if "as_of" in tile and not _is_iso(tile["as_of"]):
|
||||
raise ContractError("tile.as_of is not an ISO-8601 string")
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
"""The Workflow contract — the event kinds and the payload every approval run is told by (v0.24.0).
|
||||
|
||||
**Opt-in.** ``import dredd_core`` never loads this module, and it registers no tables (it does not
|
||||
even import :mod:`dredd_core.events`): it is a written-down shape and the two functions that make and
|
||||
read it.
|
||||
|
||||
The platform's **Workflow** module (slug ``workflow``) holds every approval run: on a Galena
|
||||
document, on a plain uploaded file, on a request (e.g. an expense). Other modules talk to it in two
|
||||
ways only — they **read its events** from the shared ``module_event`` log (Galena moves a contract
|
||||
card to "zatwierdzona") and they **start a run** on a subject with the acting person's token. Both
|
||||
sides need one definition of the kinds and the payload, so it lives here.
|
||||
|
||||
Who emits
|
||||
---------
|
||||
Only the Workflow module, as its runtime role ``workflow_app``, with ``source_module`` =
|
||||
:data:`SOURCE_MODULE`. ``source_module`` is a label anyone may write; ``source_role`` is what the
|
||||
database proved. A receiver therefore passes ``sources={kind: {"workflow_app"}}`` for each kind it
|
||||
handles to :func:`dredd_core.events.receive`, and calls :func:`parse` on every payload — a row in
|
||||
the log is untrusted input.
|
||||
|
||||
The payload
|
||||
-----------
|
||||
Identifiers and numbers only, inside :func:`dredd_core.events.check_payload`: ``run_id``,
|
||||
``actor_id``, ``subject_kind`` (one of :data:`SUBJECT_KINDS`), an optional ``stage`` and the
|
||||
subject's ids:
|
||||
|
||||
* ``document`` — ``module``, ``document_id``, ``commit_sha``, ``sha256``. **The document's path
|
||||
never enters the shared log**: a path is a file name, and every taking part module reads every
|
||||
event. The receiver reads the document by ``document_id`` + ``commit_sha`` through Galena's API.
|
||||
* ``file`` — ``file_id`` and ``sha256``. The file's display name never enters the log either.
|
||||
* ``request`` — ``request_type``, a key such as ``wydatek``.
|
||||
|
||||
Starting a run
|
||||
--------------
|
||||
:meth:`WorkflowClient.start` — ``POST /runs`` on the Workflow module through a
|
||||
:class:`dredd_core.module_client.ModuleClient`, with **the acting person's token** (keyword-only, no
|
||||
default, never a service account): Workflow's own authorization decides whether that person may
|
||||
start a run on that subject. The request body carries the whole ``document_ref.to_dict(subject)``,
|
||||
path included — it goes to one module's API, not into the shared log. An error answer is raised
|
||||
the way :meth:`~dredd_core.module_client.ModuleResponse.raise_for_status` maps it; a 2xx without a
|
||||
valid ``run_id`` and ``link`` is a :class:`~dredd_core.module_client.ModuleCallError`. The
|
||||
:class:`StartResult` link is a console route relative to the Workflow module's root
|
||||
(``#/runs/<run_id>``).
|
||||
|
||||
The engine is not here
|
||||
----------------------
|
||||
Templates, stages, who approves what: all of it lives in the Workflow module, the one home of every
|
||||
run (decided 2026-11-18). Core carries only what the two sides must agree on, so a change to how
|
||||
approvals work is a release of one module, not of the whole family.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from . import document_ref
|
||||
from .document_ref import _COMMIT, DOCUMENT_MODULES, DocumentRef, FileRef
|
||||
from .errors import ValidationError
|
||||
from .module_client import ModuleCallError, ModuleClient
|
||||
|
||||
__all__ = [
|
||||
"APPROVED",
|
||||
"CANCELLED",
|
||||
"KINDS",
|
||||
"REJECTED",
|
||||
"SIGNED_ON_PAPER",
|
||||
"SOURCE_MODULE",
|
||||
"STARTED",
|
||||
"SUBJECT_KINDS",
|
||||
"StartResult",
|
||||
"WorkflowClient",
|
||||
"WorkflowEvent",
|
||||
"parse",
|
||||
"payload",
|
||||
]
|
||||
|
||||
SOURCE_MODULE = "workflow"
|
||||
|
||||
STARTED = "workflow.started"
|
||||
APPROVED = "workflow.approved"
|
||||
REJECTED = "workflow.rejected"
|
||||
CANCELLED = "workflow.cancelled"
|
||||
SIGNED_ON_PAPER = "workflow.signed_on_paper"
|
||||
KINDS: tuple[str, ...] = (STARTED, APPROVED, REJECTED, CANCELLED, SIGNED_ON_PAPER)
|
||||
|
||||
DOCUMENT, FILE, REQUEST = "document", "file", "request"
|
||||
SUBJECT_KINDS: tuple[str, ...] = (DOCUMENT, FILE, REQUEST)
|
||||
|
||||
# The spec's [a-z0-9_]{1,40}, minus a leading "_": an event identifier starts with a letter or digit.
|
||||
_REQUEST_TYPE = re.compile(r"[a-z0-9][a-z0-9_]{0,39}")
|
||||
_MAX_STAGE = 2 ** 53
|
||||
|
||||
|
||||
def _bad(code: str, message: str) -> ValidationError:
|
||||
return ValidationError(message, {"code": code})
|
||||
|
||||
|
||||
def _uuid(value: Any, code: str) -> uuid.UUID:
|
||||
if isinstance(value, uuid.UUID):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise _bad(code, "Invalid identifier.")
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except ValueError:
|
||||
raise _bad(code, "Invalid identifier.") from None
|
||||
|
||||
|
||||
def _stage(value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= _MAX_STAGE:
|
||||
raise _bad("stage_invalid", "stage is a non-negative integer.")
|
||||
return value
|
||||
|
||||
|
||||
def _request_type(value: Any) -> str:
|
||||
if not isinstance(value, str) or not _REQUEST_TYPE.fullmatch(value):
|
||||
raise _bad("request_type_invalid", "request_type is a lower-case key of at most 40 characters.")
|
||||
return value
|
||||
|
||||
|
||||
def payload(*, run_id: uuid.UUID, subject: document_ref.Ref | None, request_type: str | None,
|
||||
actor_id: uuid.UUID, stage: int | None = None) -> dict[str, Any]:
|
||||
"""The event payload for a run on `subject`, or on a request of `request_type` — exactly one."""
|
||||
if subject is not None and request_type is not None:
|
||||
raise _bad("subject_and_request_type", "A run is on a subject or on a request, not both.")
|
||||
out: dict[str, Any] = {"run_id": str(_uuid(run_id, "run_id_invalid")),
|
||||
"actor_id": str(_uuid(actor_id, "actor_id_invalid"))}
|
||||
if isinstance(subject, DocumentRef):
|
||||
out.update(subject_kind=DOCUMENT, module=subject.module, document_id=str(subject.document_id),
|
||||
commit_sha=subject.commit_sha, sha256=subject.sha256)
|
||||
elif isinstance(subject, FileRef):
|
||||
out.update(subject_kind=FILE, file_id=str(subject.file_id), sha256=subject.sha256)
|
||||
elif subject is not None:
|
||||
raise _bad("subject_invalid", "A subject is a DocumentRef or a FileRef.")
|
||||
elif request_type is None:
|
||||
raise _bad("subject_missing", "A run is on a subject or on a request.")
|
||||
else:
|
||||
out.update(subject_kind=REQUEST, request_type=_request_type(request_type))
|
||||
if stage is not None:
|
||||
out["stage"] = _stage(stage)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkflowEvent:
|
||||
"""One Workflow event's payload, read back. The subject's fields not of its kind are ``None``."""
|
||||
|
||||
run_id: uuid.UUID
|
||||
subject_kind: str
|
||||
document_module: str | None
|
||||
document_id: uuid.UUID | None
|
||||
commit_sha: str | None
|
||||
file_id: uuid.UUID | None
|
||||
sha256: str | None
|
||||
request_type: str | None
|
||||
actor_id: uuid.UUID
|
||||
stage: int | None
|
||||
|
||||
|
||||
def parse(event_payload: Mapping[str, Any]) -> WorkflowEvent:
|
||||
"""The inverse of :func:`payload`. Anything malformed is a ``ValidationError`` with a ``code``."""
|
||||
if not isinstance(event_payload, Mapping):
|
||||
raise _bad("payload_invalid", "A Workflow event payload is an object.")
|
||||
p = event_payload
|
||||
kind = p.get("subject_kind")
|
||||
if kind not in SUBJECT_KINDS:
|
||||
raise _bad("subject_kind_invalid", "Unknown subject_kind.")
|
||||
fields: dict[str, Any] = dict(document_module=None, document_id=None, commit_sha=None,
|
||||
file_id=None, sha256=None, request_type=None)
|
||||
if kind == DOCUMENT:
|
||||
# isinstance first: `in` on a frozenset raises TypeError for an unhashable value (a list).
|
||||
if not isinstance(p.get("module"), str) or p["module"] not in DOCUMENT_MODULES:
|
||||
raise _bad("module_unknown", "Unknown document module.")
|
||||
commit = p.get("commit_sha")
|
||||
if not isinstance(commit, str) or not _COMMIT.fullmatch(commit):
|
||||
raise _bad("commit_sha_invalid", "Invalid commit id.")
|
||||
fields.update(document_module=p["module"],
|
||||
document_id=_uuid(p.get("document_id"), "document_id_invalid"),
|
||||
commit_sha=commit, sha256=document_ref.check_sha256(p.get("sha256")))
|
||||
elif kind == FILE:
|
||||
fields.update(file_id=_uuid(p.get("file_id"), "file_id_invalid"),
|
||||
sha256=document_ref.check_sha256(p.get("sha256")))
|
||||
else:
|
||||
fields.update(request_type=_request_type(p.get("request_type")))
|
||||
return WorkflowEvent(run_id=_uuid(p.get("run_id"), "run_id_invalid"), subject_kind=kind,
|
||||
actor_id=_uuid(p.get("actor_id"), "actor_id_invalid"),
|
||||
stage=_stage(p.get("stage")), **fields)
|
||||
|
||||
|
||||
_LINK = re.compile(r"#/[!-~]{1,2046}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StartResult:
|
||||
"""A started run: its id and the console route to it, relative to the module root."""
|
||||
|
||||
run_id: uuid.UUID
|
||||
link: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkflowClient:
|
||||
"""The Workflow module's API, for a module that starts runs (Galena's "Wyślij do akceptacji")."""
|
||||
|
||||
client: ModuleClient
|
||||
|
||||
def start(self, *, token: str, subject: document_ref.Ref, template_id: uuid.UUID | None = None,
|
||||
note: str | None = None) -> StartResult:
|
||||
"""Start a run on `subject` as the person whose `token` this is."""
|
||||
if not isinstance(token, str) or not token:
|
||||
raise _bad("token_missing", "Starting a run needs the acting person's token.")
|
||||
body: dict[str, Any] = {"subject": document_ref.to_dict(subject)}
|
||||
if template_id is not None:
|
||||
body["template_id"] = str(_uuid(template_id, "template_id_invalid"))
|
||||
if note is not None:
|
||||
body["note"] = note
|
||||
response = self.client.request("POST", "/runs", token=token, json=body)
|
||||
response.raise_for_status(self.client.service, "Workflow refused to start the run.")
|
||||
try:
|
||||
answer = response.json()
|
||||
run_id = uuid.UUID(answer["run_id"])
|
||||
link = answer["link"]
|
||||
except (ValueError, UnicodeDecodeError, KeyError, TypeError, AttributeError):
|
||||
run_id = link = None
|
||||
if run_id is None or not isinstance(link, str) or not _LINK.fullmatch(link):
|
||||
raise ModuleCallError(f"{self.client.service} answered without a run.",
|
||||
{"code": "bad_answer", "service": self.client.service})
|
||||
return StartResult(run_id=run_id, link=link)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "dredd-core"
|
||||
version = "0.23.1"
|
||||
version = "0.26.1"
|
||||
description = "Dredd core — the shared identity/session/auth/audit/ORM foundation for the family (Galena, Sygna, Counsel Scorecard, Galena Connect). Modules import it; it never imports a module."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""dredd_core.chat_contract — DB-free: the record and page shapes, their helpers and validators."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
import pytest
|
||||
|
||||
from dredd_core import chat_contract as cc
|
||||
|
||||
T = dt.datetime(2026, 11, 25, 10, 0, tzinfo=dt.timezone.utc)
|
||||
|
||||
|
||||
def _record(**over):
|
||||
kw = dict(module="galena", kind="umowa", id="1f0c", title="UM-2026-0017 Najem biura",
|
||||
text="Umowa UM-2026-0017 „Najem biura”,\n kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
link="cards/1f0c", labels=["UM-2026-0017", "ACME"], at=T)
|
||||
kw.update(over)
|
||||
return cc.make_record(**kw)
|
||||
|
||||
|
||||
def test_a_record_is_one_sentence_keyed_by_module_kind_and_id():
|
||||
r = _record()
|
||||
assert r == {"key": "galena:umowa:1f0c", "kind": "umowa", "title": "UM-2026-0017 Najem biura",
|
||||
"text": "Umowa UM-2026-0017 „Najem biura”, kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
"link": "cards/1f0c", "labels": ["UM-2026-0017", "ACME"],
|
||||
"at": "2026-11-25T10:00:00+00:00"}
|
||||
|
||||
|
||||
def test_optional_parts_are_left_out_and_long_text_is_cut_at_a_word():
|
||||
r = _record(labels=["", " "], at=None, text="słowo " * 1000)
|
||||
assert "labels" not in r and "at" not in r and "members" not in r
|
||||
assert len(r["text"]) <= cc.MAX_TEXT and r["text"].endswith("…")
|
||||
assert not r["text"][:-1].endswith(" ")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("over, message", [
|
||||
({"kind": "Umowa"}, "kind"),
|
||||
({"id": "a b"}, "key"),
|
||||
({"title": " "}, "title"),
|
||||
({"text": ""}, "text"),
|
||||
({"link": "#/cards/1"}, "link"),
|
||||
({"link": "https://evil.example/x"}, "link"),
|
||||
({"labels": ["x" * (cc.MAX_LABEL + 1)]}, "labels"),
|
||||
({"at": dt.datetime(2026, 11, 25)}, "timezone"),
|
||||
])
|
||||
def test_a_bad_record_is_refused_where_it_is_made(over, message):
|
||||
with pytest.raises(cc.ContractError, match=message):
|
||||
_record(**over)
|
||||
|
||||
|
||||
def test_a_record_with_keys_outside_the_contract_is_refused():
|
||||
r = dict(_record(), body="the whole contract")
|
||||
with pytest.raises(cc.ContractError, match="outside the contract"):
|
||||
cc.validate_record(r)
|
||||
|
||||
|
||||
def test_a_page_pages_through_next_offset():
|
||||
records = [_record(id=str(i)) for i in range(3)]
|
||||
first = cc.make_page("galena", records, offset=0, total=5, as_of=T)
|
||||
assert first["next_offset"] == 3 and first["version"] == 1
|
||||
last = cc.make_page("galena", records[:2], offset=3, total=5, as_of=T)
|
||||
assert last["next_offset"] is None
|
||||
assert cc.make_page("galena", [], total=0, as_of=T)["next_offset"] is None
|
||||
|
||||
|
||||
def test_a_page_holds_only_its_modules_records_each_once():
|
||||
with pytest.raises(cc.ContractError, match="names module"):
|
||||
cc.make_page("sygna", [_record()], total=1, as_of=T)
|
||||
with pytest.raises(cc.ContractError, match="twice"):
|
||||
cc.make_page("galena", [_record(), _record()], total=2, as_of=T)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("over", [
|
||||
{"version": 2}, {"module": "Galena"}, {"as_of": "yesterday"}, {"records": {}},
|
||||
{"next_offset": 0}, {"next_offset": True}, {"next_offset": "3"},
|
||||
])
|
||||
def test_a_bad_page_is_refused(over):
|
||||
page = dict(cc.make_page("galena", [_record()], total=1, as_of=T), **over)
|
||||
with pytest.raises(cc.ContractError):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
def test_next_offset_is_required_and_extra_top_level_keys_are_not_refused():
|
||||
page = cc.make_page("galena", [_record()], total=1, as_of=T)
|
||||
cc.validate_page(dict(page, hint="a module may grow"))
|
||||
page.pop("next_offset")
|
||||
with pytest.raises(cc.ContractError, match="next_offset is missing"):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
def test_too_many_records_on_a_page():
|
||||
page = cc.make_page("galena", [_record()], total=1, as_of=T)
|
||||
page["records"] = [_record(id=str(i)) for i in range(cc.MAX_RECORDS + 1)]
|
||||
with pytest.raises(cc.ContractError, match="over"):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, read", [
|
||||
((None, None), (0, cc.MAX_RECORDS)), (("-5", "0"), (0, 1)), (("20", "9999"), (20, cc.MAX_RECORDS)),
|
||||
(("x", "y"), (0, cc.MAX_RECORDS)), ((10, 50), (10, 50)),
|
||||
])
|
||||
def test_page_params_clamp_rather_than_refuse(raw, read):
|
||||
assert cc.page_params(*raw) == read
|
||||
|
||||
|
||||
def test_the_module_is_a_family_slug():
|
||||
with pytest.raises(cc.ContractError, match="slug"):
|
||||
cc.make_page("my_module", [], total=0, as_of=T)
|
||||
assert cc.make_page("m2", [], total=0, as_of=T)["module"] == "m2"
|
||||
|
||||
|
||||
def test_total_is_required_so_pagination_cannot_stop_silently():
|
||||
with pytest.raises(TypeError):
|
||||
cc.make_page("galena", [_record()], as_of=T) # type: ignore[call-arg]
|
||||
|
||||
|
||||
def test_a_long_title_is_cut_at_a_word_like_text():
|
||||
r = _record(title="tytuł " * 100)
|
||||
assert len(r["title"]) <= cc.MAX_TITLE and r["title"].endswith("…")
|
||||
assert not r["title"][:-1].endswith(" ")
|
||||
|
||||
|
||||
def test_members_are_folded_and_blank_ones_dropped_like_labels():
|
||||
r = _record(members=["galena:umowa:1", " ", "", " galena:umowa:2 "])
|
||||
assert r["members"] == ["galena:umowa:1", "galena:umowa:2"]
|
||||
with pytest.raises(cc.ContractError, match="members"):
|
||||
_record(members=["x" * (cc.MAX_MEMBER + 1)])
|
||||
|
||||
|
||||
def test_link_ok_is_public_and_the_private_name_still_works():
|
||||
from dredd_core import search_contract as sc
|
||||
assert sc.link_ok("cards/1") and not sc.link_ok("#/cards/1")
|
||||
assert sc._link_ok is sc.link_ok
|
||||
@@ -19,7 +19,12 @@ from dredd_core.identity import (
|
||||
SESSION_UPDATE_COLUMNS,
|
||||
SHARED_IDENTITY_TABLES,
|
||||
)
|
||||
from dredd_core.schema import account_delete_guard_sql, own_tables, shared_identity_grants_sql
|
||||
from dredd_core.schema import (
|
||||
account_delete_guard_sql,
|
||||
own_tables,
|
||||
session_update_guard_sql,
|
||||
shared_identity_grants_sql,
|
||||
)
|
||||
|
||||
TAG = "$dredd_shared_identity_grants$"
|
||||
FAMILY = dict(
|
||||
@@ -199,3 +204,43 @@ def test_the_delete_guard_refuses_anyone_but_the_owner_and_validates_its_names()
|
||||
assert "not the identity owner " in sql
|
||||
with pytest.raises(ValueError):
|
||||
account_delete_guard_sql("dredd", owner_role="postgres; DROP")
|
||||
|
||||
|
||||
# ── session_update_guard_sql ────────────────────────────────────────────────
|
||||
def test_the_session_guard_is_one_statement_with_no_quote_escaping():
|
||||
"""Built like the delete guard: one DO block, the trigger body and its literals dollar-quoted,
|
||||
nothing Alembic or ``text()`` would read as a parameter."""
|
||||
sql = session_update_guard_sql("dredd", owner_role="atrium_migrator", writer_role="atrium_app")
|
||||
assert sql.startswith("DO $dredd_session_update_guard$")
|
||||
assert sql.endswith("$dredd_session_update_guard$")
|
||||
assert "%" not in sql and not text(sql)._bindparams
|
||||
assert "BEFORE UPDATE ON" in sql and "FOR EACH ROW" in sql
|
||||
assert "SET search_path = pg_catalog, pg_temp" in sql
|
||||
assert "SECURITY DEFINER" not in sql
|
||||
for message in ("a revoked credential stays revoked", "only the hub extends a credential",
|
||||
"a module writes only last_seen_at, expires_at and revoked_at"):
|
||||
assert message in sql
|
||||
|
||||
|
||||
def test_the_session_guard_exempts_exactly_the_owner_and_the_writer():
|
||||
sql = session_update_guard_sql("dredd", owner_role="atrium_migrator", writer_role="atrium_app")
|
||||
assert "owner_role text := 'atrium_migrator';" in sql
|
||||
assert "writer_role text := 'atrium_app';" in sql
|
||||
assert "not the identity owner " in sql
|
||||
|
||||
|
||||
def test_the_session_guard_leaves_alone_only_the_columns_a_module_may_update():
|
||||
"""The trigger's free columns are the column grant's, so the two cannot drift apart."""
|
||||
sql = session_update_guard_sql("dredd", owner_role="atrium_migrator", writer_role="atrium_app")
|
||||
for column in SESSION_UPDATE_COLUMNS:
|
||||
assert f"$dredd_k${column}$dredd_k$" in sql
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [
|
||||
dict(owner_role="postgres; DROP", writer_role="atrium_app"),
|
||||
dict(owner_role="atrium_migrator", writer_role="atrium$app"),
|
||||
dict(owner_role="atrium_app", writer_role="atrium_app"),
|
||||
])
|
||||
def test_the_session_guard_validates_its_names(bad):
|
||||
with pytest.raises(ValueError):
|
||||
session_update_guard_sql("dredd", **bad)
|
||||
|
||||
@@ -32,7 +32,7 @@ from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Session as OrmSession
|
||||
|
||||
@@ -51,8 +51,10 @@ from dredd_core.schema import (
|
||||
create_enum_types,
|
||||
own_tables,
|
||||
runtime_grants_sql,
|
||||
session_update_guard_sql,
|
||||
shared_identity_grants_sql,
|
||||
)
|
||||
from dredd_core.security import hash_token
|
||||
from tests.conftest import refuses_with
|
||||
|
||||
# What a module of the platform configures, and what it must never configure. Both flags off is the
|
||||
@@ -144,6 +146,8 @@ def platform(db, role_prefix):
|
||||
identity, owner_role=hub.migrator, writer_role=hub.app,
|
||||
reader_roles=[module.app], migrator_roles=[module.migrator])))
|
||||
conn.execute(text(account_delete_guard_sql(identity, owner_role=hub.migrator)))
|
||||
conn.execute(text(session_update_guard_sql(identity, owner_role=hub.migrator,
|
||||
writer_role=hub.app)))
|
||||
conn.exec_driver_sql("RESET ROLE")
|
||||
|
||||
for app in (hub, module):
|
||||
@@ -261,6 +265,94 @@ def test_a_module_lists_app_tokens_it_could_never_mint(platform):
|
||||
assert [t.name for t in tokens] == ["GalenaConnect"]
|
||||
|
||||
|
||||
# ─────────────── the session guard: a module never revives or prolongs a credential ───────────────
|
||||
#
|
||||
# The column grant lets a module write revoked_at and expires_at on every row; the trigger decides
|
||||
# which values. The three tests above are the writes it must keep allowing (resolve, slide, revoke).
|
||||
|
||||
def _credential(db, raw_token: str):
|
||||
return db.scalar(select(dredd_core.Session)
|
||||
.where(dredd_core.Session.token_hash == hash_token(raw_token)))
|
||||
|
||||
|
||||
def test_a_module_cannot_undo_a_revocation(platform):
|
||||
user_id = _an_account(platform)
|
||||
token = _a_login(platform, user_id)
|
||||
with _acting_as(platform.hub, platform.hub.app, platform.identity) as db:
|
||||
AuthService(OWNER_AUTH).revoke_user_sessions(db, user_id)
|
||||
|
||||
with refuses_with("a revoked credential stays revoked"):
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
_credential(db, token).revoked_at = None
|
||||
db.flush()
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
assert AuthService(MODULE_AUTH).resolve_session_full(db, token) is None
|
||||
|
||||
|
||||
def test_a_module_cannot_extend_a_sign_in_session(platform):
|
||||
"""An interactive session dies at its TTL; no module may move that."""
|
||||
user_id = _an_account(platform)
|
||||
token = _a_login(platform, user_id)
|
||||
with refuses_with("only the hub extends a credential"):
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
row = _credential(db, token)
|
||||
row.expires_at = row.expires_at + dt.timedelta(days=3650)
|
||||
db.flush()
|
||||
|
||||
|
||||
def test_a_module_cannot_slide_an_app_token_past_its_idle_window(platform):
|
||||
user_id = _an_account(platform)
|
||||
with _acting_as(platform.hub, platform.hub.app, platform.identity) as db:
|
||||
user = db.get(dredd_core.AppUser, user_id)
|
||||
_, token = AuthService(OWNER_AUTH).create_app_token(db, user, name="GalenaConnect",
|
||||
idle_days=30)
|
||||
with refuses_with("only the hub extends a credential"):
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
row = _credential(db, token)
|
||||
row.expires_at = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=31)
|
||||
db.flush()
|
||||
|
||||
|
||||
def test_a_module_cannot_revive_an_expired_app_token(platform):
|
||||
user_id = _an_account(platform)
|
||||
with _acting_as(platform.hub, platform.hub.app, platform.identity) as db:
|
||||
user = db.get(dredd_core.AppUser, user_id)
|
||||
row, token = AuthService(OWNER_AUTH).create_app_token(db, user, name="GalenaConnect",
|
||||
idle_days=30)
|
||||
row.expires_at = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=2)
|
||||
db.flush()
|
||||
with refuses_with("only the hub extends a credential"):
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
row = _credential(db, token)
|
||||
row.expires_at = dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=1)
|
||||
db.flush()
|
||||
|
||||
|
||||
def test_the_guard_refuses_other_columns_even_behind_a_stray_grant(platform):
|
||||
"""Defence in depth: a column grant somebody added by hand still does not let a module repoint
|
||||
a credential at another account."""
|
||||
user_id, other_id = _an_account(platform), _an_account(platform)
|
||||
token = _a_login(platform, user_id)
|
||||
platform.conn.exec_driver_sql(f'SET LOCAL ROLE "{platform.hub.migrator}"')
|
||||
platform.conn.exec_driver_sql(f'GRANT UPDATE (user_id) ON "{platform.identity}".session '
|
||||
f'TO "{platform.module.app}"')
|
||||
platform.conn.exec_driver_sql("RESET ROLE")
|
||||
with refuses_with("a module writes only last_seen_at, expires_at and revoked_at"):
|
||||
with _acting_as(platform.module, platform.module.app, platform.identity) as db:
|
||||
_credential(db, token).user_id = other_id
|
||||
db.flush()
|
||||
|
||||
|
||||
def test_the_hub_is_not_bound_by_the_session_guard(platform):
|
||||
"""The writer keeps every write it has always made, prolonging included."""
|
||||
user_id = _an_account(platform)
|
||||
token = _a_login(platform, user_id)
|
||||
with _acting_as(platform.hub, platform.hub.app, platform.identity) as db:
|
||||
row = _credential(db, token)
|
||||
row.expires_at = row.expires_at + dt.timedelta(hours=1)
|
||||
db.flush()
|
||||
|
||||
|
||||
# ──────────────────── the flags refuse first; the grants refuse anyway ────────────────────
|
||||
#
|
||||
# Each pair is the same call twice: once as the module is configured, where it is a clean refusal at
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Step headers in the red-lines prompt: a rule from a skill carries the step it belongs to."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.model_access.client import RULES_CLOSE, RULES_OPEN, build_prompt
|
||||
from dredd_core.model_access.schema import build_schema
|
||||
|
||||
CLAUSES = [
|
||||
{"id": "C1", "label": "§ 1", "text": "Kara umowna wynosi 1% dziennie."},
|
||||
{"id": "C2", "label": "§ 2", "text": "Strony zawrą umowę powierzenia danych."},
|
||||
]
|
||||
RULES = [
|
||||
{"id": "kara-limit", "text": "Kara nie wyższa niż 10%.", "step_id": "kary",
|
||||
"step_name": "Kary umowne", "step_instruction": "Policz łączny limit kar."},
|
||||
{"id": "kara-zwloka", "text": "Kara za zwłokę dzienna.", "step_id": "kary",
|
||||
"step_name": "Kary umowne", "step_instruction": "Policz łączny limit kar."},
|
||||
{"id": "rodo", "text": "Jest umowa powierzenia.", "step_id": "dane",
|
||||
"step_name": "Dane osobowe", "step_instruction": ""},
|
||||
]
|
||||
|
||||
|
||||
def test_each_step_heads_its_rules_once_in_order():
|
||||
p = build_prompt(RULES, CLAUSES)
|
||||
rules_part = p.split(RULES_OPEN)[1].split(RULES_CLOSE)[0]
|
||||
assert rules_part.count("## Krok: Kary umowne") == 1
|
||||
assert rules_part.index("## Krok: Kary umowne") < rules_part.index("[kara-limit]") \
|
||||
< rules_part.index("[kara-zwloka]") < rules_part.index("## Krok: Dane osobowe") \
|
||||
< rules_part.index("[rodo]")
|
||||
assert "Policz łączny limit kar." in rules_part
|
||||
# The instruction is a lawyer's text: it must stay out of the contract and task sections.
|
||||
assert "Policz łączny limit kar." not in p.split(RULES_OPEN)[0]
|
||||
assert "Policz łączny limit kar." not in p.split(RULES_CLOSE)[1]
|
||||
|
||||
|
||||
def test_rules_without_steps_ask_byte_for_byte_as_before():
|
||||
plain = [{"id": r["id"], "text": r["text"]} for r in RULES]
|
||||
assert "## Krok:" not in build_prompt(plain, CLAUSES)
|
||||
|
||||
|
||||
def test_schema_ignores_step_keys():
|
||||
plain = [{"id": r["id"], "text": r["text"]} for r in RULES]
|
||||
assert build_schema(RULES, CLAUSES) == build_schema(plain, CLAUSES)
|
||||
@@ -8,11 +8,11 @@ from __future__ import annotations
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import select, text
|
||||
|
||||
from dredd_core import AppUser, AuditLog
|
||||
from dredd_core import model_providers as mp
|
||||
from dredd_core.errors import NotFoundError, ValidationError
|
||||
from dredd_core.errors import ConflictError, NotFoundError, ValidationError
|
||||
|
||||
QWEN = [{"id": "qwen2.5-7b-instruct", "context_window": 32768}]
|
||||
|
||||
@@ -137,6 +137,56 @@ def test_disable_never_deletes(db, actor):
|
||||
assert len(_audits(db, "model_provider.disable")) == 1
|
||||
|
||||
|
||||
def test_delete_unused_refuses_an_active_provider(db, actor):
|
||||
p = _local(db, actor)
|
||||
with pytest.raises(ConflictError) as err:
|
||||
mp.delete_unused(db, actor=actor, provider=p)
|
||||
assert err.value.extra["code"] == "provider_still_active"
|
||||
assert db.get(mp.ModelProvider, p.id) is not None
|
||||
|
||||
|
||||
def test_delete_unused_takes_the_keys_with_it_and_audits(db, actor):
|
||||
p = _api(db, actor, api_key="sk-secret-123456", encrypt=_encrypt)
|
||||
pid = p.id
|
||||
mp.disable(db, actor=actor, provider=p)
|
||||
mp.delete_unused(db, actor=actor, provider=p)
|
||||
db.expire_all()
|
||||
assert db.get(mp.ModelProvider, pid) is None
|
||||
assert db.get(mp.ModelProviderKey, pid) is None
|
||||
[row] = _audits(db, "model_provider.delete")
|
||||
assert (row.entity_id, row.detail, row.diff) == (pid, "Mistral", None)
|
||||
|
||||
|
||||
def test_delete_unused_refuses_a_provider_a_run_points_at(db, actor):
|
||||
p = _local(db, actor)
|
||||
mp.disable(db, actor=actor, provider=p)
|
||||
# A module's run table, as Arbiter's `analysis` points at its provider (rolled back with the test).
|
||||
db.execute(text("CREATE TABLE run (id int PRIMARY KEY, model_provider_id uuid "
|
||||
"REFERENCES model_provider (id) ON DELETE RESTRICT)"))
|
||||
db.execute(text("INSERT INTO run VALUES (1, :p)"), {"p": p.id})
|
||||
with pytest.raises(ConflictError) as err:
|
||||
mp.delete_unused(db, actor=actor, provider=p)
|
||||
assert err.value.extra["code"] == "provider_in_use"
|
||||
# The savepoint kept the caller's transaction alive: it still reads, and nothing was audited.
|
||||
assert db.get(mp.ModelProvider, p.id) is not None
|
||||
assert _audits(db, "model_provider.delete") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("on_delete", ["CASCADE", "SET NULL"])
|
||||
def test_delete_unused_refuses_a_foreign_key_that_would_not_restrict(db, actor, on_delete):
|
||||
p = _local(db, actor)
|
||||
mp.disable(db, actor=actor, provider=p)
|
||||
# A module that got its key wrong: deleting the provider would erase or blank this run.
|
||||
db.execute(text("CREATE TABLE careless_run (id int PRIMARY KEY, model_provider_id uuid "
|
||||
f"REFERENCES model_provider (id) ON DELETE {on_delete})"))
|
||||
db.execute(text("INSERT INTO careless_run VALUES (1, :p)"), {"p": p.id})
|
||||
with pytest.raises(ConflictError) as err:
|
||||
mp.delete_unused(db, actor=actor, provider=p)
|
||||
assert err.value.extra["code"] == "provider_reference_unsafe"
|
||||
assert "careless_run" in err.value.extra["tables"]
|
||||
assert db.execute(text("SELECT model_provider_id FROM careless_run")).scalar() == p.id
|
||||
|
||||
|
||||
# ── the policy ───────────────────────────────────────────────────────────────
|
||||
|
||||
def test_no_policy_row_fails_closed(db):
|
||||
|
||||
@@ -129,7 +129,7 @@ def _a_provider(platform) -> uuid.UUID:
|
||||
|
||||
# ──────────────────────── the tiers, as statements ────────────────────────
|
||||
|
||||
def test_the_hub_writes_everything_and_deletes_only_keys(granted):
|
||||
def test_the_hub_writes_everything_and_deletes_providers_but_not_the_policy(granted):
|
||||
pid = _a_provider(granted)
|
||||
_allowed(granted, granted.hub, "UPDATE model_provider SET is_active = false WHERE id = :p",
|
||||
{"p": pid})
|
||||
@@ -139,7 +139,7 @@ def test_the_hub_writes_everything_and_deletes_only_keys(granted):
|
||||
assert _allowed(granted, granted.hub, "SELECT api_key_encrypted FROM model_provider_key")
|
||||
_allowed(granted, granted.hub, "DELETE FROM model_provider_key WHERE provider_id = :p",
|
||||
{"p": pid})
|
||||
_denied(granted, granted.hub, "DELETE FROM model_provider WHERE id = :p", {"p": pid})
|
||||
_allowed(granted, granted.hub, "DELETE FROM model_provider WHERE id = :p", {"p": pid})
|
||||
_denied(granted, granted.hub, "DELETE FROM model_provider_policy")
|
||||
|
||||
|
||||
@@ -186,6 +186,23 @@ def test_a_modules_migrator_can_point_a_foreign_key_at_a_provider(granted):
|
||||
_denied(granted, granted.plain, "SELECT id FROM model_provider", migrator=True)
|
||||
|
||||
|
||||
def test_a_run_in_a_module_keeps_its_provider_from_the_hubs_delete(granted):
|
||||
# The guard `delete_unused` leans on: the hub may DELETE, a module's RESTRICT key still wins,
|
||||
# and the check runs as that table's owner, so the hub needs nothing on the module's schema.
|
||||
used, unused = _a_provider(granted), _a_provider(granted)
|
||||
with granted.conn.begin_nested():
|
||||
_path(granted, granted.keyed.migrator, granted.keyed.schema)
|
||||
granted.conn.exec_driver_sql(
|
||||
f'CREATE TABLE "{granted.keyed.schema}".run (id int PRIMARY KEY, model_provider_id uuid '
|
||||
f'REFERENCES "{granted.identity}".model_provider (id) ON DELETE RESTRICT)')
|
||||
granted.conn.execute(text(f'INSERT INTO "{granted.keyed.schema}".run VALUES (1, :p)'),
|
||||
{"p": used})
|
||||
granted.conn.exec_driver_sql("RESET ROLE")
|
||||
_denied(granted, granted.hub, "DELETE FROM model_provider WHERE id = :p", {"p": used},
|
||||
match="violates foreign key constraint")
|
||||
_allowed(granted, granted.hub, "DELETE FROM model_provider WHERE id = :p", {"p": unused})
|
||||
|
||||
|
||||
def test_the_service_runs_as_a_module_and_the_key_door_is_shut(granted):
|
||||
"""The service functions a module calls work on SELECT alone — and the one door to a key is
|
||||
refused by PostgreSQL, not by politeness, for a module without the opt-in."""
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""dredd_core.workflow_contract without a database: kinds, the payload rule, parse on untrusted rows."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from dredd_core import events as ev
|
||||
from dredd_core import workflow_contract as wf
|
||||
from dredd_core.document_ref import DocumentRef, FileRef
|
||||
from dredd_core.errors import AuthorizationError, ValidationError
|
||||
from dredd_core.module_client import ModuleCallError, ModuleClient
|
||||
|
||||
H = hashlib.sha256(b"umowa").hexdigest()
|
||||
COMMIT = "a" * 40
|
||||
RUN = uuid.UUID("11111111-2222-3333-4444-555555555555")
|
||||
ACTOR = uuid.UUID("99999999-8888-7777-6666-555555555555")
|
||||
DOC = uuid.UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
|
||||
FILE = uuid.UUID("12345678-1234-1234-1234-123456789abc")
|
||||
|
||||
|
||||
def _request(**over):
|
||||
base = dict(run_id=RUN, subject=None, request_type="wydatek", actor_id=ACTOR)
|
||||
return wf.payload(**{**base, **over})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", wf.KINDS)
|
||||
def test_kinds_are_valid_event_kinds(kind):
|
||||
assert ev.check_kind(kind) == kind
|
||||
|
||||
|
||||
def test_payload_document_roundtrip():
|
||||
ref = DocumentRef(document_id=DOC, path="umowy/2026/umowa z ACME.docx", commit_sha=COMMIT,
|
||||
sha256=H)
|
||||
p = wf.payload(run_id=RUN, subject=ref, request_type=None, actor_id=ACTOR, stage=2)
|
||||
assert "umowa" not in json.dumps(p) and "ACME" not in json.dumps(p)
|
||||
event = wf.parse(ev.check_payload(p))
|
||||
assert event.subject_kind == "document"
|
||||
assert (event.document_module, event.document_id, event.commit_sha, event.sha256, event.stage) \
|
||||
== ("galena", DOC, COMMIT, H, 2)
|
||||
assert (event.run_id, event.actor_id) == (RUN, ACTOR)
|
||||
assert event.file_id is None and event.request_type is None
|
||||
|
||||
|
||||
def test_payload_file_has_no_name():
|
||||
ref = FileRef(file_id=FILE, sha256=H, size=5, name="tajne.pdf")
|
||||
p = wf.payload(run_id=RUN, subject=ref, request_type=None, actor_id=ACTOR)
|
||||
assert "tajne" not in json.dumps(p)
|
||||
event = wf.parse(ev.check_payload(p))
|
||||
assert (event.subject_kind, event.file_id, event.sha256) == ("file", FILE, H)
|
||||
assert event.document_id is None and event.document_module is None and event.stage is None
|
||||
|
||||
|
||||
def test_payload_request():
|
||||
event = wf.parse(ev.check_payload(_request(stage=0)))
|
||||
assert (event.subject_kind, event.request_type, event.stage) == ("request", "wydatek", 0)
|
||||
|
||||
|
||||
def test_payload_refuses_subject_and_request_type_together():
|
||||
ref = FileRef(file_id=FILE, sha256=H, size=5, name="a.pdf")
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_request(subject=ref)
|
||||
assert exc.value.extra["code"]
|
||||
|
||||
|
||||
def test_payload_refuses_subject_and_request_type_neither():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_request(request_type=None)
|
||||
assert exc.value.extra["code"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [{"request_type": "_x"}, {"request_type": "Wydatek"}, {"stage": -1},
|
||||
{"stage": True}, {"run_id": "nope"}])
|
||||
def test_payload_refuses_bad_values(bad):
|
||||
with pytest.raises(ValidationError):
|
||||
_request(**bad)
|
||||
|
||||
|
||||
_GOOD = {"run_id": str(RUN), "actor_id": str(ACTOR), "subject_kind": "file", "file_id": str(FILE),
|
||||
"sha256": H}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
{"subject_kind": "invoice"},
|
||||
{"subject_kind": ["file"]},
|
||||
{"run_id": None},
|
||||
{"run_id": "not-a-uuid"},
|
||||
{"run_id": 12},
|
||||
{"sha256": "XYZ"},
|
||||
{"sha256": None},
|
||||
{"stage": -1},
|
||||
{"stage": "1"},
|
||||
{"subject_kind": "document", "module": ["galena"], "document_id": str(DOC), "commit_sha": COMMIT},
|
||||
{"subject_kind": "document", "module": "galena", "document_id": str(DOC), "commit_sha": "x"},
|
||||
{"subject_kind": "request"},
|
||||
])
|
||||
def test_parse_refuses_malformed(change):
|
||||
data = {k: v for k, v in {**_GOOD, **change}.items() if v is not None} # None = key missing
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
wf.parse(data)
|
||||
assert exc.value.extra["code"]
|
||||
|
||||
|
||||
def test_parse_refuses_non_mapping():
|
||||
with pytest.raises(ValidationError):
|
||||
wf.parse(["run_id"]) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_import_dredd_core_does_not_load_workflow_contract():
|
||||
code = (
|
||||
"import dredd_core, sys\n"
|
||||
"from dredd_core import Base\n"
|
||||
"assert 'dredd_core.workflow_contract' not in sys.modules\n"
|
||||
"import dredd_core.workflow_contract\n"
|
||||
"assert 'module_event' not in Base.metadata.tables\n"
|
||||
)
|
||||
subprocess.run([sys.executable, "-c", code], check=True)
|
||||
|
||||
|
||||
SEEN: list[dict] = []
|
||||
|
||||
|
||||
class Stub(BaseHTTPRequestHandler):
|
||||
"""A Workflow stand-in: /good starts a run, /empty answers 200 {}, /deny answers 403."""
|
||||
|
||||
def log_message(self, *args): # quiet
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
SEEN.append({"path": self.path, "auth": self.headers.get("Authorization"),
|
||||
"body": json.loads(self.rfile.read(length) or b"null")})
|
||||
status, answer = 404, {}
|
||||
if self.path.startswith("/good/"):
|
||||
status, answer = 201, {"run_id": str(RUN), "link": f"#/runs/{RUN}"}
|
||||
elif self.path.startswith("/empty/"):
|
||||
status = 200
|
||||
elif self.path.startswith("/deny/"):
|
||||
status, answer = 403, {"title": "Forbidden", "detail": "not yours"}
|
||||
body = json.dumps(answer).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), Stub)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _client(server, prefix):
|
||||
return wf.WorkflowClient(ModuleClient(f"{server}/{prefix}", service="Workflow"))
|
||||
|
||||
|
||||
def test_client_start_posts_with_person_token(server):
|
||||
ref = DocumentRef(document_id=DOC, path="umowy/umowa.docx", commit_sha=COMMIT, sha256=H)
|
||||
SEEN.clear()
|
||||
result = _client(server, "good").start(token="person-tok", subject=ref, note="pilne")
|
||||
assert result == wf.StartResult(run_id=RUN, link=f"#/runs/{RUN}")
|
||||
assert result.link.startswith("#/runs/")
|
||||
(seen,) = SEEN
|
||||
assert seen["path"] == "/good/api/v1/runs"
|
||||
assert seen["auth"] == "Bearer person-tok"
|
||||
assert seen["body"] == {"subject": {"kind": "document", "module": "galena",
|
||||
"document_id": str(DOC), "path": "umowy/umowa.docx",
|
||||
"commit_sha": COMMIT, "sha256": H},
|
||||
"note": "pilne"}
|
||||
|
||||
|
||||
def test_client_start_refuses_bad_2xx_body(server):
|
||||
with pytest.raises(ModuleCallError):
|
||||
_client(server, "empty").start(token="t", subject=FileRef(file_id=FILE, sha256=H, size=5, name="faktura.pdf"))
|
||||
|
||||
|
||||
def test_client_start_raises_error_answer(server):
|
||||
with pytest.raises(AuthorizationError, match="not yours"):
|
||||
_client(server, "deny").start(token="t", subject=FileRef(file_id=FILE, sha256=H, size=5, name="faktura.pdf"))
|
||||
|
||||
|
||||
def test_client_start_requires_token(server):
|
||||
client = _client(server, "good")
|
||||
ref = FileRef(file_id=FILE, sha256=H, size=5, name="faktura.pdf")
|
||||
with pytest.raises(ValidationError):
|
||||
client.start(token="", subject=ref)
|
||||
with pytest.raises(TypeError):
|
||||
client.start(subject=ref) # type: ignore[call-arg]
|
||||
Reference in New Issue
Block a user