Compare commits

...
Author SHA1 Message Date
adminandClaude Opus 5.5 b1f8f9dfba CI: allow a manual run (Actions -> CI -> Run workflow)
CI / Tests (Postgres 17) (push) Successful in 4m58s
CI / Tests (Postgres 16) (push) Successful in 5m52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:06:30 +01:00
adminandClaude Opus 5.5 b188f9cc18 CI: push runs only on main; branches are tested through their pull request [skip ci]
A push of many branches at once (the migration pushed 100 of Atrium's) started
a run per branch and flooded the runners. Every pull request is still tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:39:19 +01:00
admin 23c842b418 Merge pull request #8 from Alpaq92/fix/session-update-guard
CI / Tests (Postgres 16) (push) Successful in 9m10s
CI / Tests (Postgres 17) (push) Successful in 7m11s
session_update_guard_sql: a module never revives or prolongs a credential (0.26.1)
2026-11-28 10:39:05 +01:00
Piotr ChojnackiandClaude Opus 5.5 32aa86682e session guard: keep each message one literal, so the SQL says what the test reads
CI / Tests (Postgres 16) (push) Failing after 3s
CI / Tests (Postgres 17) (push) Failing after 3s
The column message was split across two concatenated pieces of the trigger
body. PostgreSQL joined them at run time, so the raised text was right, but the
generated SQL never contained the sentence whole and
test_the_session_guard_is_one_statement_with_no_quote_escaping failed. This
suite had never been run before (CI does not start on the account).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:51:57 +01:00
Piotr ChojnackiandClaude Opus 5.5 433e083dae Merge main (0.26.0) into the session guard; ship it as 0.26.1
The chat contract took 0.26.0 while this PR waited. The guard's code merged
cleanly. The conflicts were the version and the release notes: the version is
now 0.26.1, and "0.26.1 notes" follow main's 0.26.0 section in README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:45:16 +01:00
admin fb4867c1ad Merge pull request #7 from Alpaq92/feat/chat-contract
0.26.0: chat_contract, what a module tells the platform's chat (K4)
2026-11-28 00:21:37 +01:00
Piotr ChojnackiandClaude Opus 5.5 b9d7f83b74 session_update_guard_sql: a module never revives or prolongs a credential (0.25.1)
The reader tier's UPDATE (last_seen_at, expires_at, revoked_at) on the shared
session table covers every row and every value, so any module role could set
revoked_at = NULL on a session the hub revoked, or push expires_at to infinity
on the administrator's session.

New schema.session_update_guard_sql(): a row-level BEFORE UPDATE trigger, run
from the identity owner's revision. For every role but the owner and the
writer it refuses a change to revoked_at once 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. Sign-out, last_seen_at and the slide keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:31:11 +01:00
adminandClaude Opus 5.5 fbbbdbc53d fix(chat_contract): public link_ok, one limit rule, total required
CI / Tests (Postgres 17) (push) Failing after 2s
CI / Tests (Postgres 16) (push) Failing after 30s
search_contract.link_ok is public (the private _link_ok stays as an
alias) and chat/stats contracts use it. make_record cuts a long title at
a word like text, folds and filters members like labels, and names
MAX_MEMBER. make_page requires total, so pagination cannot stop
silently; a page without next_offset is refused by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:40:21 +01:00
adminandClaude Opus 5.5 6cd08ada43 fix(chat_contract): the module is a family slug (hyphens, never underscores)
From review: the regex let underscores through and refused a leading digit,
the opposite of module_permission's slug rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:41:50 +01:00
adminandClaude Opus 5.5 471b871248 0.26.0: chat_contract, what a module tells the platform's chat (K4)
One shape for a module's chat records: GET /chat/records answers pages
of one-sentence records (key <module>:<kind>:<id>, kind, title, text,
link, optional labels, at, members), filtered by the caller's access,
bounded, paged through next_offset. Module side: make_record, make_page,
page_params, validate_page. Opt-in, standard library only, no tables.
Atrium#53, stage 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:48:03 +01:00
admin 80d5058fa4 Merge pull request #5 into main (0.25.0)
# Conflicts:
#	README.md
#	pyproject.toml
2026-11-24 20:22:28 +01:00
tobayahandClaude Opus 5.5 ab5c16670c model_access: step headers in the red-lines prompt (0.25.0)
CI / Tests (Postgres 16) (push) Failing after 23s
CI / Tests (Postgres 17) (push) Failing after 2s
0.24.0 stays reserved for K4 (the chat).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJYwbXKWMeNZfrFuXq
2026-11-18 23:38:41 +01:00
12 changed files with 825 additions and 12 deletions
+7 -1
View File
@@ -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:
+65 -3
View File
@@ -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.24.0
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
@@ -1345,6 +1356,57 @@ person's token.
"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
+269
View File
@@ -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"])
+23 -1
View File
@@ -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"):
+136
View File
@@ -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$"""
+9 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "dredd-core"
version = "0.24.0"
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"
+133
View File
@@ -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
+46 -1
View File
@@ -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)
+93 -1
View File
@@ -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
+41
View File
@@ -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)