Merge pull request #5 from Alpaq92/fix/initiator-lock-and-round
fix(security): the initiator lock is the moderator's; a stale click fails in a new round
This commit is contained in:
@@ -335,9 +335,13 @@ the implementation plan's Part B and the module spec (paths in `.meduza/SPEC-wor
|
||||
settings (`DEFAULT_SETTINGS` + `merge_settings`, stable stage keys, notes ≤ 2000, required on
|
||||
reject / back / cancel / add_stage) and `services/engine.py` decides every action (`act()`:
|
||||
approve, reject, back, cancel, add_stage, refresh, paper_scan, edit_request) on a `RunState`.
|
||||
Refusal order is fixed: 404 -> 409 (stale `stage_key_seen` / `stages_seen`, not running) -> 403 ->
|
||||
422. Rejection follows §5.2a (back to the first or previous stage, a new round), not Galena's
|
||||
„rejection ends the run”. Keep new rules in these two files and test them DB-free.
|
||||
Refusal order is fixed: 404 -> 409 (stale `stage_key_seen` / `round_seen` / `stages_seen`, not
|
||||
running) -> 403 -> 422. Rejection follows §5.2a (back to the first or previous stage, a new round),
|
||||
not Galena's „rejection ends the run”. Keep new rules in these two files and test them DB-free.
|
||||
**The initiator lock is the moderator's**: `initiator_may_approve` is off by default, only a
|
||||
template can switch it on, and a run's `settings_override` may never lift it
|
||||
(`merge_settings(..., for_run=True)`, 422 `initiator_lock_fixed`) - otherwise anybody could lay out
|
||||
stages naming only themselves and emit `workflow.approved`, which Galena moves a card on.
|
||||
- **Who.** Read access is `services/authz.can_read_run` (a Galena document: Galena's `my_roles`
|
||||
alone; file / request: initiator, this module's moderators, the stage's people). Owner = initiator
|
||||
or Galena `manager` / moderator. Approvers are fixed on entering a stage (`run_stage_state`,
|
||||
|
||||
@@ -43,9 +43,14 @@ as a new round (§5.2a „Ustawienia obiegu”) instead of ending it.
|
||||
| `GET/POST/PATCH /admin/groups` | approver groups |
|
||||
| `GET /stats` | dredd-core `stats_contract` tiles |
|
||||
|
||||
Every action carries the stage and stage list it was decided on (`stage_key_seen` /
|
||||
`stages_seen`): a click on a run somebody else moved meanwhile is a 409, never a decision on a run
|
||||
nobody saw.
|
||||
Every action carries the stage, the round and the stage list it was decided on (`stage_key_seen` /
|
||||
`round_seen` / `stages_seen`): a click on a run somebody else moved meanwhile is a 409, never a
|
||||
decision on a run nobody saw - also when the run came back to the same stage in a new round. The
|
||||
console always sends all three; an API client that leaves out `round_seen` is not checked on it.
|
||||
|
||||
The initiator may not approve their own run unless a template allows it (`initiator_may_approve`,
|
||||
off by default). Only a moderator makes templates; the person starting a run may keep that lock or
|
||||
switch it on, never lift it (422 `initiator_lock_fixed`).
|
||||
|
||||
Standalone, the stack is published on port **8141**.
|
||||
|
||||
|
||||
@@ -154,7 +154,8 @@ def edit(request_id: uuid.UUID, request: Request, data: str = Form(...),
|
||||
body = _part(RequestPatch, data)
|
||||
edited = requests.update(db, user, request_id, title=body.title, values=body.values,
|
||||
files=files or [], note=body.note, stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, token=_token(request),
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen,
|
||||
token=_token(request),
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return edited
|
||||
|
||||
@@ -103,8 +103,8 @@ def detail(run_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
def act(run_id: uuid.UUID, body: RunActionIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
run = runs.act(db, user, run_id, action=body.action, stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, note=body.note, content_seen=body.content_seen,
|
||||
token=_token(request), ip=client_ip(request))
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen, note=body.note,
|
||||
content_seen=body.content_seen, token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return _done(run)
|
||||
|
||||
@@ -113,7 +113,7 @@ def act(run_id: uuid.UUID, body: RunActionIn, request: Request, db: Session = De
|
||||
def add_stage(run_id: uuid.UUID, body: AddStageIn, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
run = runs.act(db, user, run_id, action="add_stage", stage_key_seen=body.stage_key_seen,
|
||||
stages_seen=body.stages_seen, note=body.note,
|
||||
stages_seen=body.stages_seen, round_seen=body.round_seen, note=body.note,
|
||||
new_stage=body.stage.model_dump(mode="json", exclude_none=True),
|
||||
token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
@@ -123,12 +123,13 @@ def add_stage(run_id: uuid.UUID, body: AddStageIn, request: Request,
|
||||
@router.post("/runs/{run_id}/scan")
|
||||
def paper_scan(run_id: uuid.UUID, request: Request, file: UploadFile = File(...),
|
||||
stage_key_seen: str = Form(...), stages_seen: list[str] | None = Form(None),
|
||||
note: str | None = Form(None), db: Session = Depends(get_db),
|
||||
round_seen: int | None = Form(None), note: str | None = Form(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""The paper ending approved with the signed scan (multipart: `file` + the form fields)."""
|
||||
run = runs.act(db, user, run_id, action="paper_scan", stage_key_seen=stage_key_seen,
|
||||
stages_seen=stages_seen, note=note, scan=file, token=_token(request),
|
||||
ip=client_ip(request))
|
||||
stages_seen=stages_seen, round_seen=round_seen, note=note, scan=file,
|
||||
token=_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return _done(run)
|
||||
|
||||
|
||||
@@ -288,12 +288,13 @@ class RequestIn(In):
|
||||
|
||||
class RequestPatch(In):
|
||||
"""The JSON part of the multipart `PATCH /requests/{id}`. `values` is a partial write (a null
|
||||
value clears that field); `note` and the `*_seen` pair are the run's when one is in progress."""
|
||||
value clears that field); `note` and the `*_seen` fields are the run's when one is in progress."""
|
||||
title: str | None = None
|
||||
values: dict[str, Any] | None = None
|
||||
note: str | None = None
|
||||
stage_key_seen: str | None = None
|
||||
stages_seen: list[str] | None = None
|
||||
round_seen: int | None = None
|
||||
|
||||
|
||||
class RequestOut(BaseModel):
|
||||
@@ -351,6 +352,7 @@ class _Seen(In):
|
||||
"""What the caller saw: a click prepared before somebody else moved the run gets a 409."""
|
||||
stage_key_seen: str | None = None
|
||||
stages_seen: list[str] | None = None
|
||||
round_seen: int | None = None # the run's round; a new round is a new decision
|
||||
note: str | None = None
|
||||
|
||||
|
||||
|
||||
@@ -254,11 +254,11 @@ def apply_edit(db: DbSession, actor: AppUser, request: WorkflowRequest, *, title
|
||||
|
||||
def update(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, title: Any = None,
|
||||
values: Mapping[str, Any] | None = None, files: Sequence[subjects.Upload] = (),
|
||||
note: Any = None, stage_key_seen: Any = None, stages_seen: Any = None, token: str,
|
||||
ip: str | None = None) -> WorkflowRequest:
|
||||
note: Any = None, stage_key_seen: Any = None, stages_seen: Any = None,
|
||||
round_seen: Any = None, token: str, ip: str | None = None) -> WorkflowRequest:
|
||||
"""Edit a request as its filer or a moderator (404 for anybody else). In a run: 409 when the
|
||||
request is locked, else the run's `edit_request` (`note`, `stage_key_seen`, `stages_seen` are
|
||||
the run's). No commit."""
|
||||
request is locked, else the run's `edit_request` (`note` and the `*_seen` fields are the
|
||||
run's). No commit."""
|
||||
from . import runs # runs imports this module
|
||||
|
||||
request = db.get(WorkflowRequest, request_id)
|
||||
@@ -279,7 +279,7 @@ def update(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, title: Any =
|
||||
raise ConflictError("This request is locked while its workflow is in progress.",
|
||||
{"code": "request_locked"})
|
||||
runs.act(db, actor, run_id, action="edit_request", note=note, stage_key_seen=stage_key_seen,
|
||||
stages_seen=stages_seen, edit=edit, token=token, ip=ip)
|
||||
stages_seen=stages_seen, round_seen=round_seen, edit=edit, token=token, ip=ip)
|
||||
return request
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,12 @@ the caller's job.
|
||||
was sent and lays it over a base (the defaults, or a template's settings for a run's override), so
|
||||
a template that never touched them runs on `DEFAULT_SETTINGS`.
|
||||
|
||||
**The initiator lock is the moderator's.** By default the initiator may not approve their own run
|
||||
(`initiator_may_approve` False), so nobody ends a run approved alone. Only a template - which only a
|
||||
moderator makes - can allow it; the person starting a run may keep the lock or switch it on, never
|
||||
off (`merge_settings(..., for_run=True)`: 422 `initiator_lock_fixed`). Otherwise anybody could lay
|
||||
out their own stages naming themselves and emit `workflow.approved`, which other modules act on.
|
||||
|
||||
**Stages.** 1 to `MAX_STAGES`, each with a name (1-60 after strip), a type, who approves it and
|
||||
how many of them must (`quorum`). A role approves a stage only on a Galena document: Workflow knows
|
||||
no tree for a file or a request. The paper ending is one stage, always the last. A stage keeps the
|
||||
@@ -47,7 +53,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
"on_reject_by_approver": "previous",
|
||||
"notify_on_reject": ["owner"],
|
||||
"resolve": "on_enter",
|
||||
"initiator_may_approve": True,
|
||||
"initiator_may_approve": False,
|
||||
}
|
||||
|
||||
_POLISH = str.maketrans("ąćęłńóśźżĄĆĘŁŃÓŚŹŻ", "acelnoszzACELNOSZZ")
|
||||
@@ -144,8 +150,12 @@ _SETTING_CHECKS = {
|
||||
}
|
||||
|
||||
|
||||
def merge_settings(sent: Any, base: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""`sent` validated and laid over `base` (DEFAULT_SETTINGS when None). None sent = `base`."""
|
||||
def merge_settings(sent: Any, base: dict[str, Any] | None = None, *,
|
||||
for_run: bool = False) -> dict[str, Any]:
|
||||
"""`sent` validated and laid over `base` (DEFAULT_SETTINGS when None). None sent = `base`.
|
||||
|
||||
`for_run`: `sent` is the override of the person starting a run, who may not lift the initiator
|
||||
lock `base` keeps (422 `initiator_lock_fixed`); a template's own settings are a moderator's."""
|
||||
out = {k: (list(v) if isinstance(v, list) else v)
|
||||
for k, v in (DEFAULT_SETTINGS if base is None else base).items()}
|
||||
if sent is None:
|
||||
@@ -155,8 +165,12 @@ def merge_settings(sent: Any, base: dict[str, Any] | None = None) -> dict[str, A
|
||||
unknown = sorted(str(k) for k in sent if k not in _SETTING_CHECKS)
|
||||
if unknown:
|
||||
raise _bad("settings_unknown_key", f"Unknown setting: {', '.join(unknown)}.")
|
||||
allowed = out.get("initiator_may_approve", False)
|
||||
for key, value in sent.items():
|
||||
out[key] = _SETTING_CHECKS[key](value)
|
||||
if for_run and out.get("initiator_may_approve") and not allowed:
|
||||
raise _bad("initiator_lock_fixed",
|
||||
"Only a template can let the initiator approve their own workflow.")
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -195,10 +195,11 @@ def _layout(db: DbSession, kind: str, template_id: uuid.UUID | None, stages: Any
|
||||
template = None if template_id is None else _template(db, template_id)
|
||||
if template is None:
|
||||
laid_out = rules.stages(stages, subject_kind=kind)
|
||||
return None, laid_out, rules.merge_settings(settings_override)
|
||||
return None, laid_out, rules.merge_settings(settings_override, for_run=True)
|
||||
sent = [dict(s) for s in template.stages] if stages is None else stages
|
||||
laid_out = rules.stages(sent, subject_kind=kind, known_keys=[s["key"] for s in template.stages])
|
||||
return template, laid_out, rules.merge_settings(settings_override, template.settings)
|
||||
return template, laid_out, rules.merge_settings(settings_override, template.settings,
|
||||
for_run=True)
|
||||
|
||||
|
||||
def start(db: DbSession, actor: AppUser, *, subject: Subject, template_id: uuid.UUID | None = None,
|
||||
@@ -289,15 +290,21 @@ _TICK = dt.timedelta(microseconds=1)
|
||||
|
||||
|
||||
def assert_current(run: WorkflowRun, *, action: str, stage_key_seen: Any,
|
||||
stages_seen: Any) -> None:
|
||||
"""The 409s of an action: the run still in progress, on the stage and with the stages the
|
||||
caller saw. A click prepared before somebody else moved the run must not pass."""
|
||||
stages_seen: Any, round_seen: Any = None) -> None:
|
||||
"""The 409s of an action: the run still in progress, on the stage, in the round and with the
|
||||
stages the caller saw. A click prepared before somebody else moved the run must not pass - also
|
||||
when the run came back to the same stage in a new round (an edit of the request, a rejection on
|
||||
the first stage): the stage key is the same there, what is being approved is not."""
|
||||
if run.state != RunStatus.running.value or run.current is None:
|
||||
raise ConflictError("This workflow has already ended.", {"code": "not_running"})
|
||||
if (action in _ON_STAGE or stage_key_seen is not None) and \
|
||||
stage_key_seen != run.stages[run.current]["key"]:
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
{"code": "stage_changed"})
|
||||
if round_seen is not None and (not isinstance(round_seen, int) or isinstance(round_seen, bool)
|
||||
or round_seen != run.round):
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
{"code": "round_changed"})
|
||||
if stages_seen is not None and (not isinstance(stages_seen, list | tuple)
|
||||
or list(stages_seen) != [s["key"] for s in run.stages]):
|
||||
raise ConflictError("The workflow changed in the meantime. Refresh the view.",
|
||||
@@ -407,18 +414,20 @@ def _stage_row(db: DbSession, run_id: uuid.UUID, key: str,
|
||||
|
||||
|
||||
def act(db: DbSession, actor: AppUser, run_id: uuid.UUID, *, action: str,
|
||||
stage_key_seen: Any = None, stages_seen: Any = None, note: Any = None,
|
||||
new_stage: Any = None, content_seen: Any = None, scan: Any = None,
|
||||
stage_key_seen: Any = None, stages_seen: Any = None, round_seen: Any = None,
|
||||
note: Any = None, new_stage: Any = None, content_seen: Any = None, scan: Any = None,
|
||||
edit: dict[str, Any] | None = None, token: str, ip: str | None = None) -> WorkflowRun:
|
||||
"""Act on run `run_id` as `actor`: any of `ACTIONS`. `scan` is the paper ending's upload,
|
||||
`edit` the request changes `requests.update` hands over with `edit_request`. No commit."""
|
||||
`edit` the request changes `requests.update` hands over with `edit_request`. `round_seen` is
|
||||
checked when sent (the console always sends it). No commit."""
|
||||
if action not in ACTIONS:
|
||||
raise _bad("action_invalid", "Unknown workflow action.")
|
||||
if (action == "edit_request") != (edit is not None):
|
||||
raise _bad("edit_invalid", "A request is edited through the request.")
|
||||
run = _locked(db, run_id)
|
||||
authz.assert_can_read_run(db, actor, run, token=token)
|
||||
assert_current(run, action=action, stage_key_seen=stage_key_seen, stages_seen=stages_seen)
|
||||
assert_current(run, action=action, stage_key_seen=stage_key_seen, stages_seen=stages_seen,
|
||||
round_seen=round_seen)
|
||||
|
||||
rows = {r.stage_key: r for r in db.scalars(
|
||||
select(RunStageState).where(RunStageState.run_id == run.id))}
|
||||
|
||||
@@ -157,13 +157,14 @@ def test_a_bad_json_part_is_a_422_not_a_500(api, data):
|
||||
|
||||
|
||||
def test_patch_request_passes_the_run_fields(api):
|
||||
data = {"values": {"kwota": None}, "note": "poprawka", "stage_key_seen": "s1"}
|
||||
data = {"values": {"kwota": None}, "note": "poprawka", "stage_key_seen": "s1", "round_seen": 4}
|
||||
r = api.client.patch(f"{API}/requests/{ID}", data={"data": json.dumps(data)})
|
||||
assert r.status_code == 200, r.text
|
||||
(name, args, kwargs), = api.calls
|
||||
assert name == "update" and args[2] == ID
|
||||
assert kwargs["values"] == {"kwota": None} and kwargs["note"] == "poprawka"
|
||||
assert kwargs["stage_key_seen"] == "s1" and kwargs["files"] == []
|
||||
assert kwargs["round_seen"] == 4
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -113,12 +113,13 @@ def test_start_on_a_file_and_on_a_request(api):
|
||||
|
||||
def test_actions_pass_what_the_caller_saw(api):
|
||||
r = api.client.post(f"{API}/runs/{RUN}/actions", json={
|
||||
"action": "reject", "stage_key_seen": "s1", "stages_seen": ["s1", "s2"], "note": "nie"})
|
||||
"action": "reject", "stage_key_seen": "s1", "stages_seen": ["s1", "s2"], "round_seen": 3,
|
||||
"note": "nie"})
|
||||
assert r.status_code == 200, r.text
|
||||
(_, args, kwargs), = api.calls
|
||||
assert args[2] == RUN and kwargs["action"] == "reject" and kwargs["token"] == "t-9"
|
||||
assert (kwargs["stage_key_seen"], kwargs["stages_seen"], kwargs["note"]) == (
|
||||
"s1", ["s1", "s2"], "nie")
|
||||
assert (kwargs["stage_key_seen"], kwargs["stages_seen"], kwargs["round_seen"],
|
||||
kwargs["note"]) == ("s1", ["s1", "s2"], 3, "nie")
|
||||
|
||||
|
||||
def test_add_stage_and_scan_are_their_own_actions(api):
|
||||
@@ -126,13 +127,14 @@ def test_add_stage_and_scan_are_their_own_actions(api):
|
||||
"note": "jeszcze prawnik", "stage_key_seen": "s1",
|
||||
"stage": {"name": "Prawnik", "approver": {"kind": "users", "user_ids": [str(RUN)]}}})
|
||||
assert r.status_code == 200, r.text
|
||||
r = api.client.post(f"{API}/runs/{RUN}/scan", data={"stage_key_seen": "s2"},
|
||||
r = api.client.post(f"{API}/runs/{RUN}/scan", data={"stage_key_seen": "s2", "round_seen": "2"},
|
||||
files={"file": ("skan.pdf", io.BytesIO(b"%PDF"), "application/pdf")})
|
||||
assert r.status_code == 200, r.text
|
||||
(_, _, added), (_, _, scanned) = api.calls
|
||||
assert added["action"] == "add_stage" and added["new_stage"]["name"] == "Prawnik"
|
||||
assert "key" not in added["new_stage"]
|
||||
assert scanned["action"] == "paper_scan" and scanned["stage_key_seen"] == "s2"
|
||||
assert scanned["round_seen"] == 2 and added["round_seen"] is None
|
||||
assert scanned["scan"].filename == "skan.pdf"
|
||||
assert api.db.commits == 2
|
||||
|
||||
|
||||
@@ -83,8 +83,17 @@ def test_pinned_document_gone_keeps_run_usable(admin_client, monkeypatch):
|
||||
roles={doc: NodeRole.manager})
|
||||
monkeypatch.setattr(galena, "get", lambda: fake)
|
||||
me = admin_client.get("/api/v1/auth/me").json()["id"]
|
||||
run_id = _start(admin_client, {"kind": "document", "document_id": str(doc),
|
||||
"path": "umowa.pdf"}, me)
|
||||
# The admin approves their own run: only a template (the moderator's) may allow that.
|
||||
r = admin_client.post("/api/v1/admin/templates", json={
|
||||
"name": f"Sam {uuid.uuid4().hex[:6]}",
|
||||
"stages": [{"name": "Akceptacja", "approver": {"kind": "users", "user_ids": [me]}}],
|
||||
"settings": {"initiator_may_approve": True}})
|
||||
assert r.status_code == 201, r.text
|
||||
r = admin_client.post("/api/v1/runs", json={
|
||||
"subject": {"kind": "document", "document_id": str(doc), "path": "umowa.pdf"},
|
||||
"template_id": r.json()["id"]})
|
||||
assert r.status_code == 201, r.text
|
||||
run_id = r.json()["run_id"]
|
||||
assert admin_client.get(f"/api/v1/runs/{run_id}").json()["subject_available"] is True
|
||||
|
||||
fake.documents.clear() # the pinned version is gone from Galena
|
||||
|
||||
@@ -170,6 +170,30 @@ def test_editable_request_edit_resets_run(files):
|
||||
db.rollback()
|
||||
|
||||
|
||||
def test_a_click_from_before_an_edit_does_not_approve_the_edit(files):
|
||||
from app.db import SessionLocal
|
||||
from app.errors import ConflictError
|
||||
from app.services import requests, runs
|
||||
|
||||
with SessionLocal() as db:
|
||||
admin = _admin(db)
|
||||
approver = _approver(db)
|
||||
field, request, run = _request_in_run(db, admin, approver, editable=True)
|
||||
key = run.stages[0]["key"] # the approver reads 1000 in round 1, stage 0
|
||||
requests.update(db, admin, request.id, values={field.key: "10000"}, note="więcej",
|
||||
round_seen=1, token=TOKEN)
|
||||
db.flush()
|
||||
assert (run.current, run.round) == (0, 2) # the same stage key, a new round
|
||||
with pytest.raises(ConflictError) as err:
|
||||
runs.act(db, approver, run.id, action="approve", stage_key_seen=key, round_seen=1,
|
||||
token=TOKEN)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
runs.act(db, approver, run.id, action="approve", stage_key_seen=key, round_seen=2,
|
||||
token=TOKEN)
|
||||
assert run.current == 1
|
||||
db.rollback()
|
||||
|
||||
|
||||
def test_approved_request_cannot_be_edited(files):
|
||||
from app.db import SessionLocal
|
||||
from app.errors import ConflictError
|
||||
|
||||
@@ -40,7 +40,8 @@ def _template(db, admin, approver_id):
|
||||
"name": f"Wydatek {uuid.uuid4().hex[:6]}",
|
||||
"stages": [{"name": "Kierownik", "approver": me, "quorum": "all"},
|
||||
{"name": "Księgowość", "approver": me}],
|
||||
"settings": {"on_reject_by_approver": "end"}})
|
||||
# The moderator's template lets the initiator approve: the admin starts and approves here.
|
||||
"settings": {"on_reject_by_approver": "end", "initiator_may_approve": True}})
|
||||
|
||||
|
||||
def test_start_copies_template_stages_and_settings(files):
|
||||
@@ -154,18 +155,20 @@ def test_two_approvals_same_stage_one_wins(files):
|
||||
|
||||
with SessionLocal() as db:
|
||||
admin = _admin(db)
|
||||
run = _two_stages(db, admin, admin.id, admin.id)
|
||||
approver_id = _person(db, "zatwierdzajacy").id # the initiator may not approve by default
|
||||
run = _two_stages(db, admin, approver_id, approver_id)
|
||||
run_id, key = run.id, run.stages[0]["key"]
|
||||
db.commit() # both sessions below must see the run; it is cancelled at the end
|
||||
|
||||
barrier, outcomes = threading.Barrier(2), []
|
||||
|
||||
def approve():
|
||||
from app.models import AppUser
|
||||
with SessionLocal() as db:
|
||||
barrier.wait()
|
||||
try:
|
||||
runs.act(db, _admin(db), run_id, action="approve", stage_key_seen=key,
|
||||
token=TOKEN)
|
||||
runs.act(db, db.get(AppUser, approver_id), run_id, action="approve",
|
||||
stage_key_seen=key, token=TOKEN)
|
||||
db.commit()
|
||||
outcomes.append("ok")
|
||||
except ConflictError as err:
|
||||
|
||||
@@ -156,6 +156,33 @@ def test_notify_on_reject_values():
|
||||
assert rules.merge_settings({"notify_on_reject": []})["notify_on_reject"] == []
|
||||
|
||||
|
||||
def test_the_initiator_lock_is_on_by_default():
|
||||
assert rules.DEFAULT_SETTINGS["initiator_may_approve"] is False
|
||||
|
||||
|
||||
def test_a_run_override_may_not_lift_the_initiator_lock():
|
||||
locked = rules.merge_settings({"initiator_may_approve": False})
|
||||
for base in (None, locked):
|
||||
with pytest.raises(ValidationError) as e:
|
||||
rules.merge_settings({"initiator_may_approve": True}, base, for_run=True)
|
||||
assert code(e) == "initiator_lock_fixed"
|
||||
# Keeping the lock, or laying anything else over it, is fine.
|
||||
out = rules.merge_settings({"initiator_may_approve": False, "resolve": "live"}, locked,
|
||||
for_run=True)
|
||||
assert out["initiator_may_approve"] is False and out["resolve"] == "live"
|
||||
|
||||
|
||||
def test_a_template_may_let_the_initiator_approve_and_a_run_may_lock_it_again():
|
||||
# A template's own settings are a moderator's: no for_run there.
|
||||
allowing = rules.merge_settings({"initiator_may_approve": True})
|
||||
assert allowing["initiator_may_approve"] is True
|
||||
assert rules.merge_settings({"initiator_may_approve": True}, allowing,
|
||||
for_run=True)["initiator_may_approve"] is True
|
||||
assert rules.merge_settings({"initiator_may_approve": False}, allowing,
|
||||
for_run=True)["initiator_may_approve"] is False
|
||||
assert rules.merge_settings(None, allowing, for_run=True)["initiator_may_approve"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sent", [
|
||||
{"notify_on_reject": ["boss"]}, {"notify_on_reject": ["user:nope"]}, {"notify_on_reject": "owner"},
|
||||
{"on_reject_by_owner": "later"}, {"on_reject_by_approver": None}, {"resolve": "sometimes"},
|
||||
|
||||
@@ -278,6 +278,31 @@ def test_initiator_lock_refuses_a_stage_only_the_initiator_approves():
|
||||
assert err.value.extra["code"] == "initiator_only_approver"
|
||||
|
||||
|
||||
def test_initiator_lock_is_on_without_a_template():
|
||||
# Own stages naming only the initiator: nobody else could approve, and they may not.
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject=FILE, stages=[_users(ME)], token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_only_approver"
|
||||
|
||||
|
||||
def test_the_initiator_may_not_lift_the_lock_when_starting():
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject=FILE, stages=[_users(ME)],
|
||||
settings_override={"initiator_may_approve": True}, token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_lock_fixed"
|
||||
template = SimpleNamespace(id=uuid.uuid4(), name="Wydatek", archived=False,
|
||||
settings=dict(runs.rules.DEFAULT_SETTINGS),
|
||||
stages=[{"key": "k", "name": "Kierownik", "type": "zatwierdzenie",
|
||||
"approver": {"kind": "users", "user_ids": [str(OTHER)]},
|
||||
"quorum": "one"}])
|
||||
db = _Db(objects={template.id: template})
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(db, _actor(), subject=FILE, template_id=template.id, stages=[_users(ME)],
|
||||
settings_override={"initiator_may_approve": True}, token=TOKEN)
|
||||
assert err.value.extra["code"] == "initiator_lock_fixed"
|
||||
assert db.writes == []
|
||||
|
||||
|
||||
def test_unknown_subject_is_422():
|
||||
with pytest.raises(ValidationError) as err:
|
||||
runs.start(_Db(), _actor(), subject={"kind": "file"}, stages=[_users(OTHER)], token=TOKEN)
|
||||
@@ -368,6 +393,28 @@ def test_act_409_stale_stages(monkeypatch, seen):
|
||||
assert err.value.extra["code"] == "stages_changed"
|
||||
|
||||
|
||||
def test_assert_current_refuses_a_click_from_another_round():
|
||||
# An edit of the request or a rejection on the first stage brings the run back to the SAME
|
||||
# stage key in a new round: the key alone would let a click from before approve what came after.
|
||||
run = _run(current=0, round=2)
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=["a", "b"],
|
||||
round_seen=2)
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=None) # not sent
|
||||
for stale in (1, 3, True, "2"):
|
||||
with pytest.raises(ConflictError) as err:
|
||||
runs.assert_current(run, action="approve", stage_key_seen="a", stages_seen=None,
|
||||
round_seen=stale)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
|
||||
|
||||
def test_act_409_stale_round_before_403(monkeypatch):
|
||||
db = _acting(monkeypatch) # round 1; LATER may not approve stage a, so the 409 comes first
|
||||
with pytest.raises(ConflictError) as err:
|
||||
_act(db, LATER, round_seen=0)
|
||||
assert err.value.extra["code"] == "round_changed"
|
||||
assert db.writes == []
|
||||
|
||||
|
||||
def test_cancel_checks_the_stage_only_when_sent(monkeypatch):
|
||||
db = _acting(monkeypatch)
|
||||
with pytest.raises(ConflictError) as err:
|
||||
|
||||
+17
-9
@@ -783,7 +783,7 @@ function layoutChanged() {
|
||||
$('lpPreview').classList.toggle('hidden', own);
|
||||
$('lpEditor').innerHTML = !own ? '' : `<div class="field" style="margin:16px 0 8px">Etapy</div>
|
||||
${stageEditor('lpStages', t ? t.stages : [], { allowRole: state.start.allowRole, groups: state.start.groups })}
|
||||
${settingsEditor('lpSet', t ? t.settings : null)}
|
||||
${settingsEditor('lpSet', t ? t.settings : null, true)}
|
||||
${isModerator() ? `<div class="row" style="margin-top:12px"><button type="button" class="btn" onclick="saveLayoutAsTemplate()">${svg(ICN.plus)}Zapisz jako szablon</button></div>` : ''}`;
|
||||
localize($('lpEditor'));
|
||||
}
|
||||
@@ -972,10 +972,15 @@ const ACTION = { // [label, note required] — rules.NOTE_REQUIRED
|
||||
approve: ['Zatwierdź', false], paper_scan: ['Zatwierdź ze skanem', false], reject: ['Odrzuć', true],
|
||||
back: ['Cofnij', true], cancel: ['Anuluj obieg', true], refresh: ['Odśwież zatwierdzających', false],
|
||||
};
|
||||
const STALE = ['stage_changed', 'stages_changed', 'not_running'];
|
||||
const STALE = ['stage_changed', 'stages_changed', 'round_changed', 'not_running'];
|
||||
const shortHash = (h) => (h ? String(h).slice(0, 12) : '');
|
||||
const stageAt = (i) => (i == null ? null : _run.stages[i]);
|
||||
const seen = () => ({ stage_key_seen: _run.stages[_run.current].key, stages_seen: _run.stages.map((s) => s.key) });
|
||||
/* The round too: a run sent back to the same stage (a request edit, a rejection on the first stage)
|
||||
keeps its stage key, and a click from before must not approve what came after. */
|
||||
const seen = () => ({
|
||||
stage_key_seen: _run.stages[_run.current].key, stages_seen: _run.stages.map((s) => s.key),
|
||||
round_seen: _run.round,
|
||||
});
|
||||
|
||||
/* runs.pinned: what a content review confirms — a document's commit, else the file's hash, else
|
||||
(a request) the snapshot hash on the newest timeline entry, since an edit re-snapshots it. */
|
||||
@@ -1183,6 +1188,7 @@ function doAction(action) {
|
||||
form.append('file', file);
|
||||
form.append('stage_key_seen', s.stage_key_seen);
|
||||
s.stages_seen.forEach((k) => form.append('stages_seen', k));
|
||||
form.append('round_seen', String(s.round_seen));
|
||||
if (note) form.append('note', note);
|
||||
await apiForm(`/runs/${id}/scan`, form);
|
||||
return;
|
||||
@@ -1272,7 +1278,7 @@ const MAX_STAGES = 10;
|
||||
authority (a template saved from here carries every key explicitly). */
|
||||
const DEFAULT_RUN_SETTINGS = {
|
||||
on_reject_by_owner: 'first', on_reject_by_approver: 'previous', notify_on_reject: ['owner'],
|
||||
resolve: 'on_enter', initiator_may_approve: true,
|
||||
resolve: 'on_enter', initiator_may_approve: false,
|
||||
};
|
||||
|
||||
/* One editor per container id; the start screens and "Dodaj etap" reuse it. The rows live in the
|
||||
@@ -1361,13 +1367,15 @@ function moveStage(id, i, d) {
|
||||
setStages(id, s);
|
||||
}
|
||||
|
||||
/* §5.2a „Ustawienia obiegu”, collapsed by default: most templates never touch them. */
|
||||
function settingsEditor(id, current) {
|
||||
/* §5.2a „Ustawienia obiegu”, collapsed by default: most templates never touch them. `forRun`: the
|
||||
start screen, where the initiator may keep or switch on the template's initiator lock but never
|
||||
lift it (rules.merge_settings for_run) - so the box is off and disabled when the base locks. */
|
||||
function settingsEditor(id, current, forRun) {
|
||||
const s = Object.assign({}, DEFAULT_RUN_SETTINGS, current);
|
||||
const n = s.notify_on_reject || [];
|
||||
const people = n.filter((t) => t.startsWith('user:')).map((t) => t.slice(5));
|
||||
const box = (f, on, label) =>
|
||||
`<label class="row"><input type="checkbox" data-f="${f}"${on ? ' checked' : ''} />${label}</label>`;
|
||||
const box = (f, on, label, off) =>
|
||||
`<label class="row"><input type="checkbox" data-f="${f}"${on ? ' checked' : ''}${off ? ' disabled' : ''} />${label}</label>`;
|
||||
return `<details id="${id}" class="adv"><summary>Zaawansowane</summary>
|
||||
<div class="grid2">
|
||||
<label class="field">Gdy odrzuca inicjator lub zarządca<select data-f="owner">${options(REJECT_TO, s.on_reject_by_owner)}</select></label>
|
||||
@@ -1378,7 +1386,7 @@ function settingsEditor(id, current) {
|
||||
${box('n_owner', n.includes('owner'), 'Właściciel obiegu')}
|
||||
${box('n_initiator', n.includes('initiator'), 'Inicjator')}
|
||||
${multi('data-f="n_users"', userPairs(people), people)}</div>
|
||||
${box('self', s.initiator_may_approve, 'Inicjator może zatwierdzać')}
|
||||
${box('self', s.initiator_may_approve, 'Inicjator może zatwierdzać', forRun && !s.initiator_may_approve)}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user