Review gate: Combine versions and Resolve discrepancies move versions by the policy's rules

* An editor could merge their working version straight into the main version of a project that
  needs approval with "Combine versions" (POST /projects/{id}/combine), which needed `editor` only:
  the review policy's whole promise, gone for anybody who can edit. The same route merged into
  someone else's working version, the source of their open draft, and POST /projects/{id}/versions
  could create that version in advance. `changes.assert_may_write_version` is the one rule for
  both routes: the main version of a `review_required` project is moved by an approver or a
  manager (D4: the approver role is the whole rule), someone else's `version/...` by a manager.
* "Resolve discrepancies" wrote around the write chokepoint: it published a draft that was already
  rejected or withdrawn, wrote any path it was handed (files nobody reviewed, committed under
  "Publish draft"), and committed an encrypted file's resolved text in plain text. It now needs an
  open draft, writes only the files the draft changes, encrypts under the file's mode (a passphrase
  file is refused, it cannot be encrypted without the passphrase), and the conflict picker shows
  the decrypted text instead of ciphertext. `git add` gets `--` before the path.

DB-free regression tests in tests/test_review_gate.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Piotr Chojnacki
2026-11-26 00:56:46 +01:00
co-authored by Claude Opus 5.5
parent 1138421e05
commit cdc728e83a
5 changed files with 304 additions and 22 deletions
+5
View File
@@ -305,6 +305,11 @@ From a project's **History** you can **Combine versions** — merge one version'
(not necessarily the main version). You pick a source and a target version; a clean merge applies
immediately, and an overlapping one reports the discrepancies.
Two targets are not an editor's to combine into: the **main version of a project that needs
approval** (only an approver or a manager may; for everybody else the way in is a draft), and
**someone else's working version** (it is the source of their draft; only a manager may). The same
goes for creating someone else's working version in advance.
---
## 13. Clone
+5 -4
View File
@@ -33,7 +33,8 @@ def _draft(db: Session, draft_id: uuid.UUID) -> tuple[Draft, Node]:
def create_version(project_id: uuid.UUID, name: str, from_ref: str = git_facade.MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
role = authz.assert_role(db, user, project, NodeRole.editor)
changes.assert_may_write_version(user, project, name, role)
git_facade.create_version(project.id, name, from_ref)
return {"ok": True, "version": name}
@@ -43,14 +44,14 @@ def combine(project_id: uuid.UUID, body: CombineIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Combine versions: merge one version into another (not necessarily the main version)."""
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
role = authz.assert_role(db, user, project, NodeRole.editor)
if body.source == body.target:
raise ConflictError("Pick two different versions to combine.")
versions = git_facade.list_versions(project.id)
if body.source not in versions or body.target not in versions:
raise NotFoundError("Unknown version.")
result = changes.combine_versions(db, user, project, body.source, body.target,
body.message, ip=client_ip(request))
body.message, ip=client_ip(request), role=role)
db.commit()
return result
@@ -142,7 +143,7 @@ def conflict(draft_id: uuid.UUID, path: str, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.approver)
return git_facade.conflict_sides(project.id, draft.source_version, path, draft.target_version)
return changes.conflict_sides(project, draft, path)
@router.post("/drafts/{draft_id}/resolve")
+70 -4
View File
@@ -21,7 +21,7 @@ from ..enums import (
PrincipalType,
ReviewPolicy,
)
from ..errors import ConflictError, NotFoundError, ValidationError
from ..errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
from ..models import AppUser, Draft, DraftMessage, Node
from . import audit, authz, crypto, events, git_facade, notify, settings
from .git_facade import MAIN
@@ -234,11 +234,46 @@ def publish_draft(db: DbSession, approver: AppUser, project: Node, draft: Draft,
return {"ok": True, "sha": result["sha"]}
def conflict_sides(project: Node, draft: Draft, path: str) -> dict:
"""The main version's and the draft's copy of one file, as text, for Resolve discrepancies.
Decrypted like every other read: git holds ciphertext for an encrypted file, and showing it
would hand the approver noise to choose from - noise that `resolve_and_publish` would then
commit as the file. A passphrase file needs its passphrase, so it answers the same 422 as
opening it does."""
path = git_facade.safe_path(path)
def side(ref: str) -> str:
if not git_facade.file_exists(project.id, path, ref):
return ""
return crypto.decrypt(git_facade.read_file(project.id, path, ref)).decode("utf-8", "replace")
return {"path": path, "main": side(draft.target_version), "incoming": side(draft.source_version)}
def resolve_and_publish(db: DbSession, approver: AppUser, project: Node, draft: Draft,
resolutions: dict[str, bytes], ip: str | None = None) -> dict:
"""Publish a draft whose merge overlaps, with the approver's content for the files it touches.
A write like any other, so it keeps what `apply_change` keeps: only an OPEN draft (the same rule
as `publish_draft`; a rejected or withdrawn one is not a second chance), and the file's
encryption - the resolved content is encrypted under the file's mode before it reaches git, or
an encrypted contract would land on the main version in plain text. Which paths may be written
is `git_facade.resolve_publish`'s rule: only the files the draft changes."""
if draft.status != DraftStatus.open:
raise ConflictError("This draft is already closed.")
blobs: dict[str, bytes] = {}
for raw_path, content in resolutions.items():
path = git_facade.safe_path(raw_path)
mode = _effective_mode(db, project, path)
if mode == EncryptionMode.passphrase:
raise ValidationError("This file is protected by a passphrase, so it can't be resolved "
"here. Edit it in the draft's working version instead.")
blobs[path] = content if mode == EncryptionMode.none \
else crypto.encrypt(db, project.id, path, content, mode)
git_facade.set_committer(*settings.committer(db))
result = git_facade.resolve_publish(
project.id, draft.source_version, draft.target_version, resolutions,
project.id, draft.source_version, draft.target_version, blobs,
author_name=approver.full_name, author_email=approver.email,
message=f"Publish draft (resolved): {draft.title}",
)
@@ -314,10 +349,41 @@ def withdraw_draft(db: DbSession, user: AppUser, draft: Draft) -> Draft:
return draft
#: Every working version is `version/<slug of its owner's e-mail>` (`working_branch`).
WORKING_PREFIX = "version/"
def assert_may_write_version(user: AppUser, project: Node, version: str, role: NodeRole) -> None:
"""May `user`, holding `role` on `project`, merge into (or create) the version `version`?
Two lines a plain editor does not move, whatever route they take:
* **the main version of a `review_required` project** - that it changes only when an approver
publishes a draft is the whole promise of the policy, and "Combine versions" into it was a
way round that promise for anybody with `editor`. An approver may (D4: the approver role is
the whole rule; they could submit and publish a draft of their own anyway).
* **someone else's working version** - it is the source of that person's draft, so a merge into
it puts content into a draft its author never wrote and an approver then publishes as theirs.
Creating one in advance is the same thing: their first save lands on top of it. A manager may
(they manage the project, and can change its policy anyway).
"""
rank = NodeRole.rank(role)
if (version == MAIN and ReviewPolicy(project.review_policy) == ReviewPolicy.review_required
and rank < NodeRole.rank(NodeRole.approver)):
raise AuthorizationError("This project needs approval: its main version changes only when "
"an approver publishes a draft.")
if (version.startswith(WORKING_PREFIX) and version != working_branch(user)
and rank < NodeRole.rank(NodeRole.manager)):
raise AuthorizationError("That is someone else's working version.")
def combine_versions(db: DbSession, user: AppUser, project: Node, source: str, target: str,
message: str | None = None, ip: str | None = None) -> dict:
message: str | None = None, ip: str | None = None, *,
role: NodeRole) -> dict:
"""Merge one version into another (branch→branch, not necessarily main) — 'Combine versions'.
Returns {ok, sha} or {ok: False, conflicts: [...]} just like publish."""
`role` is the caller's on the project; `assert_may_write_version` decides whether the target is
theirs to move. Returns {ok, sha} or {ok: False, conflicts: [...]} just like publish."""
assert_may_write_version(user, project, target, role)
git_facade.set_committer(*settings.committer(db))
result = git_facade.publish(
project.id, source, target, author_name=user.full_name, author_email=user.email,
+9 -14
View File
@@ -560,25 +560,18 @@ def publish(project_id: uuid.UUID, source: str, target: str = MAIN, *,
return {"ok": True, "sha": repo.head.commit.hexsha}
def conflict_sides(project_id: uuid.UUID, source: str, path: str, target: str = MAIN) -> dict:
"""The 'main version' (target) and 'your version' (source) contents of a conflicting file —
powers the Resolve discrepancies picker."""
ours = read_file(project_id, path, target) if file_exists(project_id, path, target) else b""
theirs = read_file(project_id, path, source) if file_exists(project_id, path, source) else b""
return {
"path": path,
"main": ours.decode("utf-8", "replace"),
"incoming": theirs.decode("utf-8", "replace"),
}
def resolve_publish(project_id: uuid.UUID, source: str, target: str, resolutions: dict[str, bytes],
*, author_name: str, author_email: str | None, message: str) -> dict:
"""Complete a conflicted merge using the chosen content per path (Resolve discrepancies)."""
"""Complete a conflicted merge using the chosen content per path (Resolve discrepancies).
Only a file the draft changes - one that differs between `target` and `source`, the very list
the draft's page shows and the console offers to resolve - may be given content here. Anything
else would be a file nobody reviewed, written into the target under "Publish draft"."""
repo = _repo(project_id)
source, target = _ref(source), _ref(target)
with _lock(project_id):
repo.git.checkout(target)
changed = {p for p in repo.git.diff("--name-only", target, source).splitlines() if p.strip()}
with repo.git.custom_environment(
GIT_AUTHOR_NAME=author_name, GIT_AUTHOR_EMAIL=author_email or "user@localhost",
GIT_COMMITTER_NAME=_committer.name, GIT_COMMITTER_EMAIL=_committer.email,
@@ -590,10 +583,12 @@ def resolve_publish(project_id: uuid.UUID, source: str, target: str, resolutions
try:
for raw_path, content in resolutions.items():
path = safe_path(raw_path)
if path not in changed:
raise ValidationError("Only the files this draft changes can be resolved.")
full = _full_path(repo.working_tree_dir, path)
full.parent.mkdir(parents=True, exist_ok=True)
full.write_bytes(content)
repo.git.add(path)
repo.git.add("--", path)
if _conflicted_paths(repo):
raise ValidationError("Some discrepancies are still unresolved.")
repo.git.commit("-m", message)
+215
View File
@@ -0,0 +1,215 @@
"""The review gate holds on every route that moves a version, DB-free.
* "Combine versions" may not put content on the main version of a `review_required` project for a
plain editor (that is what a published draft is for), nor into someone else's working version,
the source of their draft; creating someone else's working version in advance is the same thing.
* "Resolve discrepancies" is a write like any other: only for an open draft, only the files the
draft changes, and encrypted files stay encrypted.
A fake session stands in for SQLAlchemy, as in `test_write_paths.py`: it answers "no row" to every
lookup and keeps what is added, plus the `file_crypto` markers.
"""
from __future__ import annotations
import base64
import os
import types
import uuid
import pytest
from app.enums import DraftStatus, EncryptionMode, NodeRole, ReviewPolicy
from app.errors import AuthorizationError, ConflictError, ValidationError
from app.models import Draft, FileCrypto
from app.services import changes, crypto, notify
from app.services import git_facade as g
class _FakeDB:
def __init__(self):
self.added = []
def execute(self, _statement):
pass
def get(self, _model, _key):
return None
def scalar(self, _stmt):
return None
def add(self, obj):
self.added.append(obj)
def flush(self):
pass
def delete(self, obj):
self.added.remove(obj)
@pytest.fixture(autouse=True)
def markers(monkeypatch):
def get_crypto(db, project_id, path):
return next((r for r in db.added if isinstance(r, FileCrypto)
and r.project_id == project_id and r.path == path), None)
monkeypatch.setattr(crypto, "get_crypto", get_crypto)
monkeypatch.setattr(notify, "notify_author", lambda *a, **k: None)
@pytest.fixture
def master_key(monkeypatch):
monkeypatch.setattr(crypto.settings, "encryption_master_key",
base64.b64encode(os.urandom(32)).decode())
def _user(email="ada@example.com"):
return types.SimpleNamespace(id=uuid.uuid4(), email=email, full_name="Ada")
def _project(policy=ReviewPolicy.review_required, mode=EncryptionMode.none):
pid = uuid.uuid4()
g.init_project(pid)
return types.SimpleNamespace(id=pid, name="P", review_policy=policy, encryption_mode=mode)
def _commit(pid, path, data, branch=g.MAIN):
return g.commit_file(pid, path, data, branch=branch, author_name="T", author_email="t@e.com",
message="m")
# ── who may move a version ────────────────────────────────────────────────────
ADA, BEN = _user("ada@example.com"), _user("ben@example.com")
ADAS, BENS = changes.working_branch(ADA), changes.working_branch(BEN)
@pytest.mark.parametrize("policy,version,role,allowed", [
# the main version of a project that needs approval: approvers and up only
(ReviewPolicy.review_required, g.MAIN, NodeRole.editor, False),
(ReviewPolicy.review_required, g.MAIN, NodeRole.approver, True),
(ReviewPolicy.review_required, g.MAIN, NodeRole.manager, True),
# an open project's main version is where every editor's save lands anyway
(ReviewPolicy.open, g.MAIN, NodeRole.editor, True),
# someone else's working version: managers only
(ReviewPolicy.review_required, BENS, NodeRole.editor, False),
(ReviewPolicy.review_required, BENS, NodeRole.approver, False),
(ReviewPolicy.open, BENS, NodeRole.editor, False),
(ReviewPolicy.review_required, BENS, NodeRole.manager, True),
# one's own working version and an ordinary named version: any editor
(ReviewPolicy.review_required, ADAS, NodeRole.editor, True),
(ReviewPolicy.review_required, "feature", NodeRole.editor, True),
])
def test_who_may_move_a_version(policy, version, role, allowed):
project = types.SimpleNamespace(id=uuid.uuid4(), review_policy=policy)
if allowed:
changes.assert_may_write_version(ADA, project, version, role)
else:
with pytest.raises(AuthorizationError):
changes.assert_may_write_version(ADA, project, version, role)
def test_an_editor_cannot_combine_their_version_into_main_under_review():
db, project = _FakeDB(), _project()
_commit(project.id, "umowa.md", b"base")
changes.apply_change(db, ADA, project, "umowa.md", b"unreviewed", message="m") # -> ADAS
with pytest.raises(AuthorizationError):
changes.combine_versions(db, ADA, project, ADAS, g.MAIN, role=NodeRole.editor)
assert g.read_file(project.id, "umowa.md", g.MAIN) == b"base"
assert not [r for r in db.added if getattr(r, "action", None) == "combine"]
def test_an_editor_cannot_combine_into_someone_elses_working_version():
db, project = _FakeDB(), _project()
_commit(project.id, "umowa.md", b"base")
changes.apply_change(db, BEN, project, "umowa.md", b"ben's draft", message="m") # -> BENS
g.create_version(project.id, "feature")
_commit(project.id, "extra.md", b"slipped in", branch="feature")
with pytest.raises(AuthorizationError):
changes.combine_versions(db, ADA, project, "feature", BENS, role=NodeRole.editor)
assert not g.file_exists(project.id, "extra.md", BENS)
def test_an_approver_may_still_combine_into_main_and_it_is_audited():
db, project = _FakeDB(), _project()
_commit(project.id, "umowa.md", b"base")
g.create_version(project.id, "feature")
_commit(project.id, "umowa.md", b"agreed", branch="feature")
out = changes.combine_versions(db, ADA, project, "feature", g.MAIN, role=NodeRole.approver)
assert out["ok"] is True
assert g.read_file(project.id, "umowa.md", g.MAIN) == b"agreed"
assert [r.action for r in db.added if hasattr(r, "action")] == ["combine"]
# ── Resolve discrepancies ─────────────────────────────────────────────────────
def _conflicted(project, main=b"main side", feature=b"feature side", path="umowa.md"):
"""`path` changed on both main and `feature` since they parted: a merge conflicts."""
_commit(project.id, path, b"base")
g.create_version(project.id, "feature")
_commit(project.id, path, main)
_commit(project.id, path, feature, branch="feature")
return Draft(id=uuid.uuid4(), project_id=project.id, title="D", author_id=BEN.id,
source_version="feature", target_version=g.MAIN, status=DraftStatus.open)
@pytest.mark.parametrize("status", [DraftStatus.rejected, DraftStatus.withdrawn,
DraftStatus.published])
def test_a_closed_draft_cannot_be_published_by_resolving_it(status):
db, project = _FakeDB(), _project()
draft = _conflicted(project)
draft.status = status
with pytest.raises(ConflictError):
changes.resolve_and_publish(db, ADA, project, draft, {"umowa.md": b"resolved"})
assert g.read_file(project.id, "umowa.md", g.MAIN) == b"main side"
def test_resolving_writes_only_the_files_the_draft_changes():
db, project = _FakeDB(), _project()
draft = _conflicted(project)
with pytest.raises(ValidationError):
changes.resolve_and_publish(db, ADA, project, draft,
{"umowa.md": b"resolved", "aneks.md": b"nobody reviewed this"})
assert g.read_file(project.id, "umowa.md", g.MAIN) == b"main side"
assert not g.file_exists(project.id, "aneks.md", g.MAIN)
assert draft.status == DraftStatus.open
# The refused merge was aborted: the next resolve starts from a clean tree and succeeds.
out = changes.resolve_and_publish(db, ADA, project, draft, {"umowa.md": b"resolved"})
assert out["ok"] is True and g.read_file(project.id, "umowa.md", g.MAIN) == b"resolved"
def test_a_resolved_encrypted_file_stays_encrypted(master_key):
db, project = _FakeDB(), _project(mode=EncryptionMode.server)
enc = lambda data: crypto.encrypt(db, project.id, "umowa.md", data, EncryptionMode.server)
draft = _conflicted(project, main=enc(b"main side"), feature=enc(b"feature side"))
# The picker shows the text, not ciphertext an approver would otherwise "choose".
sides = changes.conflict_sides(project, draft, "umowa.md")
assert (sides["main"], sides["incoming"]) == ("main side", "feature side")
changes.resolve_and_publish(db, ADA, project, draft, {"umowa.md": b"resolved"})
blob = g.read_file(project.id, "umowa.md", g.MAIN)
assert crypto.is_encrypted_blob(blob) and crypto.decrypt(blob) == b"resolved"
def test_a_passphrase_file_is_not_resolved_in_plain_text():
db, project = _FakeDB(), _project()
blob = lambda data: crypto.encrypt(db, project.id, "umowa.md", data,
EncryptionMode.passphrase, "sekret")
draft = _conflicted(project, main=blob(b"main side"), feature=blob(b"feature side"))
with pytest.raises(ValidationError):
changes.resolve_and_publish(db, ADA, project, draft, {"umowa.md": b"resolved"})
assert crypto.is_encrypted_blob(g.read_file(project.id, "umowa.md", g.MAIN))