Merge pull request #48 into main
This commit is contained in:
@@ -21,6 +21,7 @@ from .enums import SessionKind, TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import skills as skill_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
|
||||
@@ -145,3 +146,12 @@ def require_administrator(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
if not user.is_admin:
|
||||
raise AuthorizationError("This area is for administrators.")
|
||||
return user
|
||||
|
||||
|
||||
def require_skill_approver(user: AppUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)) -> AppUser:
|
||||
"""Whoever decides publish requests: an administrator, or an approver on the firm's workspace.
|
||||
Wider than `require_administrator` on purpose; the rule itself is `skills.may_approve`."""
|
||||
if not skill_service.may_approve(db, user):
|
||||
raise AuthorizationError("This area is for approvers.")
|
||||
return user
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""A person's skills and agents: list, read, write versions, archive, publish, export and import —
|
||||
and the administrator's queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
and the approvers' queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
|
||||
No access rule lives here. Skills are not org-tree nodes, so `authz` has nothing to say about them;
|
||||
`services/skills.py` is the one place that decides who sees and changes what (its docstring says why
|
||||
@@ -18,7 +18,7 @@ from fastapi.routing import APIRoute
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_administrator
|
||||
from ..deps import client_ip, get_current_user, require_skill_approver
|
||||
from ..models import AppUser
|
||||
from ..schemas import AgentCreateIn, AgentVersionIn, NoteIn, SkillCreateIn, SkillVersionIn
|
||||
from ..services import skills as service
|
||||
@@ -108,6 +108,12 @@ def import_skills(request: Request, filename: str | None = Query(default=None, m
|
||||
return out
|
||||
|
||||
|
||||
# Before `/{skill_id}`, which would take "permissions" for an id and answer 422.
|
||||
@router.get("/permissions")
|
||||
def permissions(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return {"approve": service.may_approve(db, user)}
|
||||
|
||||
|
||||
@router.get("/{skill_id}")
|
||||
def get_skill(skill_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
@@ -226,18 +232,18 @@ def export_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(de
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
# The service checks the administrator again; the guard here is what keeps the routes out of reach
|
||||
# The service checks the approver again; the guard here is what keeps the routes out of reach
|
||||
# of anybody else before a database is touched.
|
||||
@publish_requests.get("")
|
||||
def pending_publish_requests(db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
admin: AppUser = Depends(require_skill_approver)) -> list[dict]:
|
||||
return service.pending_publish_requests(db, admin)
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/approve")
|
||||
def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=True,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
@@ -247,7 +253,7 @@ def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None
|
||||
@publish_requests.post("/{request_id}/decline")
|
||||
def decline_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=False,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
|
||||
+10
-1
@@ -342,13 +342,22 @@ SmallJson = Annotated[dict[str, Any] | None, AfterValidator(_small_json)]
|
||||
|
||||
|
||||
class SkillVersionIn(BaseModel):
|
||||
"""A new version. `None` = carried over from the newest one; `files: {}` removes them all."""
|
||||
"""A new version. `None` = carried over from the base version; `files: {}` removes them all.
|
||||
|
||||
The base is `base_n` when given (the version the person was looking at, which they must be able
|
||||
to read: Ruling 15). Without it, Ruling 9: the actor's own newest version if it is newer than
|
||||
the current one, else the current one, else the owner's newest. Never "the newest overall",
|
||||
which may be somebody else's proposal."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
description: str | None = Field(default=None, max_length=2000)
|
||||
body: str | None = Field(default=None, max_length=60_000)
|
||||
license: str | None = Field(default=None, max_length=200)
|
||||
metadata: SmallJson = None
|
||||
files: SkillFiles = Field(default=None, max_length=200)
|
||||
# path -> base64: the previous version's files with these replaced or added. Not with `files`.
|
||||
file_updates: SkillFiles = Field(default=None, max_length=200)
|
||||
# The version this one is made on (the one the person was looking at); None = the default base.
|
||||
base_n: int | None = Field(default=None, ge=1)
|
||||
|
||||
|
||||
class SkillCreateIn(SkillVersionIn):
|
||||
|
||||
+169
-47
@@ -11,7 +11,17 @@ business. An administrator gets no exception here: a personal skill is a lawyer'
|
||||
and an administrator sees one only inside a publish request (the publication path, not this one).
|
||||
|
||||
Who may CHANGE one (`can_edit`): the owner, and for a firm skill also an administrator. Everybody
|
||||
else makes a personal copy.
|
||||
else may PROPOSE on an active firm skill (`can_propose`): a new version that waits for approval.
|
||||
A proposer reads the current version and the versions they wrote themselves, nothing more
|
||||
(`readable_version_ids`); only an editor reads every version. A proposer's publish is always a
|
||||
request, and so is anybody's publish of a version a non-editor wrote (`publish_skill`).
|
||||
|
||||
Who decides a publish request (`may_approve`): an administrator, or somebody holding `approver` or
|
||||
better on the firm's workspace node of the org tree. The existing grant screen hands that out, so
|
||||
there is no second permission table. A role on a group or folder is not the firm's. An approver who
|
||||
is not an editor reads one more version than a proposer: the one sitting in a PENDING request,
|
||||
because they cannot decide on what they cannot read (`_readable_version`). Once decided, the
|
||||
request grants nothing.
|
||||
|
||||
Versions are frozen
|
||||
-------------------
|
||||
@@ -21,8 +31,8 @@ import is — it is packed with `skill_pack.build_pack` and read back with `skil
|
||||
a skill typed in the console and one uploaded as a ZIP obey the same rules and hash the same way.
|
||||
|
||||
`current_version_id` of a PERSONAL skill follows its newest version. A FIRM skill's is the approved
|
||||
one, and only publication moves it — a new version of a firm skill stays invisible to everybody but
|
||||
its editors until then.
|
||||
one, and only publication moves it — a new version of a firm skill is readable only by its editors
|
||||
and its author until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -40,6 +50,8 @@ from sqlalchemy.orm import Session as DbSession
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
NodeKind,
|
||||
NodeRole,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
@@ -51,12 +63,13 @@ from ..models import (
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
AppUser,
|
||||
Node,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
from . import audit, settings, skill_pack
|
||||
from . import audit, authz, settings, skill_pack
|
||||
from .marketplace import _clean_note
|
||||
from .skill_pack import PackRejected, SkillContent
|
||||
|
||||
@@ -84,6 +97,13 @@ def can_edit(user: AppUser, item) -> bool:
|
||||
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
|
||||
|
||||
|
||||
def can_propose(user: AppUser, item) -> bool:
|
||||
"""Whoever may edit, and anybody for an active firm skill: a new version is a proposal there
|
||||
(`_add_version` never moves a firm skill's current version; only an approval does)."""
|
||||
return can_edit(user, item) or (item.scope == SkillScope.firm
|
||||
and item.status == CatalogStatus.active)
|
||||
|
||||
|
||||
def visible_to(db: DbSession, user: AppUser) -> list[Skill]:
|
||||
"""Every skill `user` may see — `can_see` as SQL. Archived ones included: an agent may still pin
|
||||
one, and the console says so."""
|
||||
@@ -107,11 +127,34 @@ def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
return skill
|
||||
|
||||
|
||||
def readable_version_ids(user: AppUser, skill: Skill, version_ids) -> set[uuid.UUID]:
|
||||
"""An editor reads every version; anybody else only the current (for a firm skill: approved)."""
|
||||
def _get_proposable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = _get(db, user, skill_id)
|
||||
if not can_propose(user, skill):
|
||||
raise AuthorizationError("Only the owner or an administrator may change this skill.")
|
||||
return skill
|
||||
|
||||
|
||||
def may_approve(db: DbSession, user: AppUser) -> bool:
|
||||
"""May `user` decide publish requests? An administrator, or `approver`+ on any workspace node.
|
||||
The workspace is the firm (the root of the org tree), and a grant there reaches everything
|
||||
below; a grant on a group or folder does not make anyone the firm's approver. The role is
|
||||
resolved by `authz.effective_role` and compared by dredd-core's rank, never by its string."""
|
||||
if user.is_admin:
|
||||
return True
|
||||
needed = NodeRole.rank(NodeRole.approver)
|
||||
return any(NodeRole.rank(authz.effective_role(db, user, node)) >= needed
|
||||
for node in db.scalars(select(Node).where(Node.kind == NodeKind.workspace)))
|
||||
|
||||
|
||||
def readable_version_ids(user: AppUser, skill: Skill, versions) -> set[uuid.UUID]:
|
||||
"""The ids among `versions` this person may read. An editor reads every version. Anybody else
|
||||
reads the current one (for a firm skill: approved) and the versions they wrote themselves, so a
|
||||
proposer sees their own proposal but not other people's, nor the owner's earlier personal
|
||||
drafts of a skill that later became the firm's."""
|
||||
if can_edit(user, skill):
|
||||
return set(version_ids)
|
||||
return {skill.current_version_id} & set(version_ids)
|
||||
return {v.id for v in versions}
|
||||
return {v.id for v in versions
|
||||
if v.id == skill.current_version_id or v.created_by == user.id}
|
||||
|
||||
|
||||
# ---- content -----------------------------------------------------------------------------------
|
||||
@@ -200,7 +243,8 @@ def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
|
||||
return {"id": skill.id, "slug": skill.slug, "name": skill.name, "owner_id": skill.owner_id,
|
||||
"scope": skill.scope, "status": skill.status, "origin": skill.origin,
|
||||
"current_version_id": skill.current_version_id, "mine": skill.owner_id == user.id,
|
||||
"editable": can_edit(user, skill)}
|
||||
"editable": can_edit(user, skill),
|
||||
"proposable": can_propose(user, skill)}
|
||||
|
||||
|
||||
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
|
||||
@@ -225,7 +269,7 @@ def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
skill = _get(db, user, skill_id)
|
||||
versions = list(db.scalars(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc())))
|
||||
readable = readable_version_ids(user, skill, (v.id for v in versions))
|
||||
readable = readable_version_ids(user, skill, versions)
|
||||
current = next((v for v in versions if v.id == skill.current_version_id), None)
|
||||
return {**skill_out(user, skill),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at,
|
||||
@@ -235,22 +279,36 @@ def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
if current is not None and current.id in readable else None)}
|
||||
|
||||
|
||||
def _pending_for_approver(db: DbSession, user: AppUser, version: SkillVersion) -> bool:
|
||||
"""A version waiting in a publish request is readable by whoever may decide that request."""
|
||||
return bool(db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == PublishKind.skill, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending))) and may_approve(db, user)
|
||||
|
||||
|
||||
def _readable_version(db: DbSession, user: AppUser, skill_id: uuid.UUID,
|
||||
n: int) -> tuple[Skill, SkillVersion]:
|
||||
"""The skill and its version `n`, if this person may read it — an unapproved firm version is a
|
||||
404 to others."""
|
||||
skill = _get(db, user, skill_id)
|
||||
"""The skill and its version `n`, if this person may read it; an unapproved firm version is a
|
||||
404 to others. The one exception to `can_see`: an approver reads a version in a pending request
|
||||
even of somebody's personal skill, because the request is what puts it in front of them."""
|
||||
skill = db.get(Skill, skill_id)
|
||||
if skill is None:
|
||||
raise NotFoundError("Skill not found.")
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is None or not readable_version_ids(user, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return skill, version
|
||||
if version is not None:
|
||||
if can_see(user, skill) and readable_version_ids(user, skill, [version]):
|
||||
return skill, version
|
||||
if _pending_for_approver(db, user, version):
|
||||
return skill, version
|
||||
# A personal skill nobody may see stays "Skill not found", as `_get` says.
|
||||
raise NotFoundError("Version not found." if can_see(user, skill) else "Skill not found.")
|
||||
|
||||
|
||||
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
|
||||
"""Version `n`, if this person may read it. `approved_for_firm` tells the checking service
|
||||
whether this is the version the firm approved: an editor can read a proposal too, and a check
|
||||
run against one must not pass as the firm's own. An archived skill has no approved version:
|
||||
whether this is the version the firm approved: an editor or the author can read a proposal, and a
|
||||
check run against one must not pass as the firm's own. An archived skill has no approved version:
|
||||
archiving is the firm's kill switch, and the checking service reads this flag fresh on every
|
||||
real-contract order, so it stops there at once."""
|
||||
skill, version = _readable_version(db, user, skill_id, n)
|
||||
@@ -291,29 +349,75 @@ def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | No
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
def _base_version(db: DbSession, actor: AppUser, skill: Skill) -> SkillVersion:
|
||||
"""What an unset field is carried over from. NOT the newest version overall: that may be a
|
||||
stranger's proposal, which an editor's next save would then inherit unseen. The base is the
|
||||
actor's own newest version when it is newer than the current one (or nothing is current yet),
|
||||
else the current version, else the newest one the owner wrote."""
|
||||
mine = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
current = (db.get(SkillVersion, skill.current_version_id)
|
||||
if skill.current_version_id is not None else None)
|
||||
if mine is not None and (current is None or mine.n > current.n):
|
||||
return mine
|
||||
if current is not None:
|
||||
return current
|
||||
owners = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == skill.owner_id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
if owners is None:
|
||||
# Every skill starts with its owner's version 1, so this is not expected; failing beats
|
||||
# falling back to the newest version overall, which may be a stranger's proposal.
|
||||
raise ConflictError("This skill has no version to build on.")
|
||||
return owners
|
||||
|
||||
|
||||
def _named_base(db: DbSession, actor: AppUser, skill: Skill, n: int) -> SkillVersion:
|
||||
"""Version `n` as the base, when the caller names the one it was looking at (the console's
|
||||
editor always does): an explicit choice, so Ruling 9's worry (inheriting a stranger's proposal
|
||||
unseen) does not apply. It must still be a version this person may read, with the same 404."""
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return version
|
||||
|
||||
|
||||
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`. A field that is None is carried over from the newest version (`files`
|
||||
included — `{}` is how to remove them all). An imported licence is the author's: it stays."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
"""Version `n + 1`. A field that is None is carried over from the base version: `base_n` when
|
||||
given (`_named_base`), else `_base_version` (the actor's own newer one, else the current one —
|
||||
never a stranger's proposal); `files`
|
||||
included — `{}` is how to remove them all). `file_updates` (path -> bytes) instead replaces or
|
||||
adds just those files and carries every other one over byte for byte, so a caller that holds
|
||||
one file need not hold the rest. An imported licence is the author's: it stays. On a firm skill
|
||||
this is a proposal: it waits for publication like any other new version."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
if skill.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived skill takes no new versions.")
|
||||
if fields.get("files") is not None and fields.get("file_updates") is not None:
|
||||
raise ValidationError("Send files or file_updates, not both.")
|
||||
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
license = fields.get("license") or latest.license
|
||||
base = (_named_base(db, actor, skill, fields["base_n"]) if fields.get("base_n") is not None
|
||||
else _base_version(db, actor, skill))
|
||||
license = fields.get("license") or base.license
|
||||
if skill.origin == SkillOrigin.imported:
|
||||
license = latest.license
|
||||
license = base.license
|
||||
files = fields.get("files")
|
||||
if files is None:
|
||||
files = {f.path: f.content for f in _files(db, latest.id)}
|
||||
if fields.get("name"):
|
||||
files = {f.path: f.content for f in _files(db, base.id)}
|
||||
files.update(fields.get("file_updates") or {})
|
||||
# The name sits on the identity row, outside versioning: a proposal must not rename a firm skill.
|
||||
if fields.get("name") and can_edit(actor, skill):
|
||||
skill.name = fields["name"]
|
||||
version = _add_version(
|
||||
db, actor, skill, next_n(latest.n),
|
||||
description=fields.get("description") or latest.description,
|
||||
body=fields["body"] if fields.get("body") is not None else latest.body_md,
|
||||
description=fields.get("description") or base.description,
|
||||
body=fields["body"] if fields.get("body") is not None else base.body_md,
|
||||
license=license,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else latest.meta,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else base.meta,
|
||||
files=files)
|
||||
_audit(db, actor, "skill.version", skill, version, ip=ip)
|
||||
return version_out(version, _files(db, version.id))
|
||||
@@ -339,15 +443,17 @@ def _make_current(item, version) -> None:
|
||||
|
||||
|
||||
def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
ip: str | None) -> dict:
|
||||
ip: str | None, request_only: bool = False) -> dict:
|
||||
"""`approval` -> a request for THIS version (every version, not only the first); `direct` ->
|
||||
published now. The item stays where it was until an administrator says yes."""
|
||||
published now. The item stays where it was until an administrator says yes. `request_only`:
|
||||
a proposer who may not edit never publishes on their own, and neither does an editor publishing
|
||||
a version a non-editor wrote: both file a request, whatever the setting says."""
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
if item.scope == SkillScope.firm and item.current_version_id == version.id:
|
||||
raise ConflictError("This version is already published.")
|
||||
target = f"{getattr(item, 'slug', item.name)} v{version.n}"
|
||||
if settings.get(db, "skills_firm_publish") == "direct":
|
||||
if not request_only and settings.get(db, "skills_firm_publish") == "direct":
|
||||
_make_current(item, version)
|
||||
db.flush()
|
||||
# No request and nobody else's yes: the setting is the approval, the detail says so.
|
||||
@@ -357,7 +463,7 @@ def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
if db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == kind, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending)):
|
||||
raise ConflictError("This version is already waiting for an administrator.")
|
||||
raise ConflictError("This version is already waiting for an approver.")
|
||||
req = PublishRequest(kind=kind.value, version_id=version.id, requested_by=actor.id,
|
||||
status=PublishRequestStatus.pending.value)
|
||||
db.add(req)
|
||||
@@ -370,22 +476,30 @@ def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
def publish_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Publish version `n` (default: the newest) to the firm — by the owner, or for a firm skill
|
||||
also by an administrator."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
also by an administrator. Without `n` it is the actor's OWN newest version, never a stranger's.
|
||||
It goes live directly (setting `direct`) only when the actor may edit AND so could the version's
|
||||
author; anything else — a proposer's publish, or an editor publishing a proposal — is a request."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.order_by(SkillVersion.n.desc()).limit(1))
|
||||
else query.where(SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = db.scalar(query)
|
||||
if version is None:
|
||||
# A non-editor publishes only what they wrote; anything else is as unreadable (and as 404) to
|
||||
# them as a read of it would be, so no number can be probed and no draft lands in the queue.
|
||||
if version is None or (not can_edit(actor, skill) and version.created_by != actor.id):
|
||||
raise NotFoundError("Version not found.")
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip),
|
||||
author = db.get(AppUser, version.created_by)
|
||||
request_only = not (can_edit(actor, skill) and author is not None and can_edit(author, skill))
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip,
|
||||
request_only=request_only),
|
||||
"skill": skill_out(actor, skill)}
|
||||
|
||||
|
||||
def _require_administrator(actor: AppUser) -> None:
|
||||
def _require_approver(db: DbSession, actor: AppUser) -> None:
|
||||
# The router guards too; this is what keeps someone's personal skill out of other hands.
|
||||
if not actor.is_admin:
|
||||
raise AuthorizationError("Only an administrator decides publish requests.")
|
||||
if not may_approve(db, actor):
|
||||
raise AuthorizationError("Only an approver decides publish requests.")
|
||||
|
||||
|
||||
def _resolve(db: DbSession, req: PublishRequest):
|
||||
@@ -404,8 +518,11 @@ def refuses_older(item, current_n: int | None, version) -> bool:
|
||||
|
||||
def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, approve: bool,
|
||||
note: str | None = None, ip: str | None = None) -> dict:
|
||||
"""An administrator's yes or no. Yes moves the firm's current version to the requested one."""
|
||||
_require_administrator(actor)
|
||||
"""An approver's yes or no. Yes moves the firm's current version to the requested one. An
|
||||
approver who is not an administrator never decides a request they filed, nor one for a version
|
||||
they wrote (an owner's publish of an approver's proposal is a request, Ruling 10): that is the
|
||||
second pair of eyes. An administrator may, as before."""
|
||||
_require_approver(db, actor)
|
||||
# Row lock: two administrators deciding the same request at once must not both "win".
|
||||
req = db.scalar(select(PublishRequest).where(PublishRequest.id == request_id)
|
||||
.with_for_update())
|
||||
@@ -413,7 +530,12 @@ def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, appr
|
||||
raise NotFoundError("Request not found.")
|
||||
if req.status != PublishRequestStatus.pending:
|
||||
raise ConflictError("This request has already been decided.")
|
||||
own = "You cannot decide your own request."
|
||||
if req.requested_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
item, version = _resolve(db, req)
|
||||
if version.created_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
if approve:
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
@@ -458,9 +580,9 @@ def _full_version(db: DbSession, kind: str, version) -> dict:
|
||||
|
||||
|
||||
def pending_publish_requests(db: DbSession, actor: AppUser) -> list[dict]:
|
||||
"""Every pending request, oldest first — the one place an administrator sees somebody else's
|
||||
personal skill, and only the version put forward."""
|
||||
_require_administrator(actor)
|
||||
"""Every pending request, oldest first: the one place an approver sees somebody else's personal
|
||||
skill, and only the version put forward (which `_readable_version` lets them read as well)."""
|
||||
_require_approver(db, actor)
|
||||
rows = db.scalars(select(PublishRequest).where(
|
||||
PublishRequest.status == PublishRequestStatus.pending).order_by(PublishRequest.created_at))
|
||||
return [_request_out(db, r) for r in rows]
|
||||
@@ -579,7 +701,7 @@ def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | No
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.id == skill.current_version_id))
|
||||
version = db.scalar(query)
|
||||
if version is None or not readable_version_ids(actor, skill, [version.id]):
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
raise NotFoundError("Version not found.")
|
||||
data = skill_pack.build_pack([version_content(skill, version, _files(db, version.id))])
|
||||
audit.record(db, action="skill.export", entity_type="skill", entity_id=skill.id,
|
||||
@@ -604,7 +726,7 @@ def may_pin(user: AppUser, agent_scope: str, skill: Skill | None, version: Skill
|
||||
# ponytail: only the CURRENT published version — an older approved one is refused too;
|
||||
# remembering which versions were approved would lift that, if repinning annoys.
|
||||
return skill.scope == SkillScope.firm and version.id == skill.current_version_id
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version.id]))
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version]))
|
||||
|
||||
|
||||
def _check_pins(db: DbSession, user: AppUser, agent_scope: str, ids) -> list[SkillVersion]:
|
||||
|
||||
@@ -173,7 +173,7 @@ test('module prefixes match only at a segment boundary', () => {
|
||||
test('a malformed module hash shows "not found" instead of throwing', async () => {
|
||||
const calls = [];
|
||||
const env = { state: { user: {}, stale: false }, location: { hash: '#/m/%zz/x' },
|
||||
closeWaffle() {}, refreshShared() {}, showFrame: (...a) => calls.push(a) };
|
||||
closeWaffle() {}, refreshShared() {}, leavingDraft: () => false, showFrame: (...a) => calls.push(a) };
|
||||
const router = new Function(...Object.keys(env), fnBody('async function router() {') + '\nreturn router;')(...Object.values(env));
|
||||
await router();
|
||||
assert.deepEqual(calls, [['', 'x']]);
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
// Run by test_skills_console.py: `node trial_loop.mjs <app.js>`. It lifts the Próba tab's section out
|
||||
// of the console and drives `runVersionLoop` against a scripted `arbiter()`, so the rule "after a 504,
|
||||
// never a POST beside the step still running" is asserted by behaviour, not by grepping for strings.
|
||||
// Time is faked: `setTimeout` fires at once and `Date.now()` is a clock the script moves.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const SRC = readFileSync(process.argv[2], 'utf8');
|
||||
const START = "/* ── a skill version's trial and standards check (Próba) ──";
|
||||
const i = SRC.indexOf(START);
|
||||
assert.ok(i >= 0, 'the Próba section is not in app.js');
|
||||
const SECTION = SRC.slice(i, SRC.indexOf('/* ── import ──', i));
|
||||
|
||||
const http = (status, detail) => Object.assign(new Error(detail), { status, problem: { detail } });
|
||||
const trialState = (contracts, extra = {}) => ({
|
||||
version_n: 2, ran_at: 'r' + contracts, contracts, of: 15, complete: contracts === 15,
|
||||
rules: contracts * 4, agree: contracts * 4, differ: 0,
|
||||
results: Array.from({ length: contracts }, (_, k) => ({ contract: 'c' + k, status: 'answered' })),
|
||||
...extra,
|
||||
});
|
||||
const agentWith = (st) => ({ id: 'A', skill_trials: { AV: st } });
|
||||
|
||||
/* One run of the loop over `script`: a list of [expected call, reply]. A call off the script is
|
||||
recorded and refused, so the run ends with it in `calls` and in `t.runErr`. */
|
||||
async function run(script, { clock = { now: 0 }, onGet = () => {}, start = trialState(3) } = {}) {
|
||||
const calls = [];
|
||||
const t = { version: 'V1', loading: false, status: { trial: start }, err: null, running: null, stop: false, runErr: null };
|
||||
const state = { _skillView: { s: { id: 'S' }, shown: { id: 'V1', n: 2 } }, _trials: { V1: t }, _trial: t };
|
||||
const arbiter = async (method, path) => {
|
||||
const call = method + ' ' + path;
|
||||
calls.push(call);
|
||||
const next = script.shift();
|
||||
if (!next || next[0] !== call) throw new Error('unexpected call: ' + call);
|
||||
if (method === 'GET') { clock.now += 16 * 60 * 1000; onGet(t, calls, state); }
|
||||
if (next[1] instanceof Error) throw next[1];
|
||||
return next[1];
|
||||
};
|
||||
const env = {
|
||||
state, arbiter, enc: encodeURIComponent, _tr: (x) => x,
|
||||
renderSkillBody() {}, setTimeout: (fn) => fn(), Date: { now: () => clock.now },
|
||||
};
|
||||
const fns = new Function(...Object.keys(env), SECTION + '\nreturn { runVersionLoop };')(...Object.values(env));
|
||||
await fns.runVersionLoop('trial');
|
||||
return { calls, t, script };
|
||||
}
|
||||
|
||||
const SYNC = ['POST skills/S/versions/2/sync', { agent_id: 'A', agent_version_id: 'AV', n: 2, approved_for_firm: false }];
|
||||
const STEP = 'POST agents/A/trial?agent_version_id=AV';
|
||||
const READ = 'GET agents/A';
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push([name, fn]);
|
||||
|
||||
test('after a 504 the next step waits until a re-read shows the cut-off step landed', async () => {
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))], // the cut-off step still running: nothing new yet
|
||||
[READ, agentWith(trialState(4))], // it landed
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'no error is shown');
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a contract judged again (no new row, a new ran_at) counts as landed', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3, { ran_at: 'later' }))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('"Zatrzymaj" during the wait still waits for the step, then posts nothing more', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
], { onGet: (tr, cs) => { if (cs.length === 3) tr.stop = true; } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.contracts, 4);
|
||||
});
|
||||
|
||||
test('a step that never lands is waited for at most the cap, then one POST shows the refusal', async () => {
|
||||
// Each read moves the clock 16 minutes; the cap is 125, so the eighth read is past it.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(409, 'The model is busy with another step.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr.status, 409);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('signing out during the wait ends the loop without another POST', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
], { onGet: (tr, cs, st) => { st._trials = {}; } }); // what showLogin() does
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('a retry that is cut off again and never lands stops with a message, not a third POST', async () => {
|
||||
// Each wait runs out the cap (8 reads of 16 minutes); a model server that never answers would
|
||||
// otherwise get a paid call every 125 minutes for ever.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads.map((r) => [...r]),
|
||||
], { onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, ...reads.map((r) => r[0])]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.ok(t.runErr && t.runErr.slow, 'the "taking too long" message is shown');
|
||||
assert.equal(t.runErr.message, 'Ten krok trwa zbyt długo. Sprawdź serwer modelu i spróbuj ponownie.');
|
||||
assert.ok(running.every((r) => r === 'trial'), 'the button stays disabled through both waits');
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('a capped retry that lands carries on as usual', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a read that fails during the wait (502, network) keeps waiting, the button disabled', async () => {
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(502, 'Bad Gateway')],
|
||||
[READ, new TypeError('Failed to fetch')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 }, onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'a failed read is not the run\'s error');
|
||||
assert.ok(running.every((r) => r === 'trial'));
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('reads that keep failing still end at the cap, then one POST', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, http(502, 'Bad Gateway')]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a 4xx during the wait ends the run: the next POST would be refused just the same', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(401, 'Not authenticated.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr.status, 401);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
let failed = 0;
|
||||
for (const [name, fn] of tests) {
|
||||
try { await fn(); console.log('ok ' + name); } catch (e) { failed++; console.log('FAIL ' + name + '\n' + e.stack); }
|
||||
}
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -158,7 +158,9 @@ def test_cores_english_sentence_is_used_in_english(console):
|
||||
"""Core's refusals carry `detail` in Polish and `en` in English next to a stable `code`; the
|
||||
console's source language is Polish, so EN readers get core's own sentence."""
|
||||
api = console.split("async function api(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "coreRefusal(data)" in api
|
||||
assert "throw httpError(res, data)" in api # the refusal is worded in one place for api() and arbiter()
|
||||
refused = console.split("function httpError(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "coreRefusal(data)" in refused
|
||||
body = console.split("function coreRefusal(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "problem.en" in body and "LANG === SRC_LANG" in body
|
||||
|
||||
|
||||
@@ -127,6 +127,16 @@ def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
|
||||
assert fields["description"] is None and fields["metadata"] is None # None = carry over
|
||||
|
||||
|
||||
def test_a_new_version_passes_base_n_and_refuses_one_below_1(api):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 3})
|
||||
assert r.status_code == 201, r.text
|
||||
(_, fields), _ = api.calls["new_version"]
|
||||
assert fields["base_n"] == 3
|
||||
del api.calls["new_version"]
|
||||
assert api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 0}).status_code == 422
|
||||
assert "new_version" not in api.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
{"a.txt": "not base64!"},
|
||||
["a.txt"],
|
||||
@@ -153,7 +163,8 @@ def test_every_agent_and_publish_request_route_is_registered_under_the_api_prefi
|
||||
("GET", "/agents"), ("POST", "/agents"), ("GET", "/agents/{agent_id}"),
|
||||
("POST", "/agents/{agent_id}/versions"), ("POST", "/agents/{agent_id}/archive"),
|
||||
("POST", "/agents/{agent_id}/publish"), ("GET", "/agents/{agent_id}/export"),
|
||||
("POST", "/agents/import"), ("GET", "/admin/publish-requests"),
|
||||
("POST", "/agents/import"), ("GET", "/skills/permissions"),
|
||||
("GET", "/admin/publish-requests"),
|
||||
("POST", "/admin/publish-requests/{request_id}/approve"),
|
||||
("POST", "/admin/publish-requests/{request_id}/decline"),
|
||||
]:
|
||||
@@ -166,15 +177,17 @@ def _calls(dependant):
|
||||
yield from _calls(d)
|
||||
|
||||
|
||||
def test_every_publish_request_route_depends_on_require_administrator():
|
||||
def test_every_publish_request_route_depends_on_require_skill_approver():
|
||||
routes = [r for r in app.routes
|
||||
if isinstance(r, APIRoute) and r.path.startswith(API + "/admin/publish-requests")]
|
||||
assert len(routes) == 3
|
||||
for r in routes:
|
||||
assert deps.require_administrator in set(_calls(r.dependant)), r.path
|
||||
assert deps.require_skill_approver in set(_calls(r.dependant)), r.path
|
||||
assert deps.require_administrator not in set(_calls(r.dependant)), r.path
|
||||
|
||||
|
||||
def test_a_non_administrator_is_refused_the_publish_queue(api):
|
||||
def test_somebody_who_may_not_approve_is_refused_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: False)
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 403
|
||||
|
||||
@@ -187,3 +200,16 @@ def test_a_new_agent_version_passes_pins_and_leaves_absent_fields_none(api, monk
|
||||
r = api.client.post(f"{API}/agents/{SKILL_ID}/versions", json={"skill_version_ids": [str(pin)]})
|
||||
assert r.status_code == 201, r.text
|
||||
assert seen["skill_version_ids"] == [pin] and seen["instructions"] is None
|
||||
|
||||
|
||||
def test_an_approver_who_is_not_an_administrator_reaches_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
monkeypatch.setattr(service, "pending_publish_requests", lambda _db, _actor: [])
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 200 and r.json() == []
|
||||
|
||||
|
||||
def test_permissions_route_is_not_swallowed_by_skill_id(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
r = api.client.get(f"{API}/skills/permissions")
|
||||
assert r.status_code == 200 and r.json() == {"approve": True}
|
||||
|
||||
@@ -8,12 +8,16 @@ address. That the routes behave is `test_skills_integration.py`'s job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -171,12 +175,17 @@ def _text_builders(screen: str) -> str:
|
||||
|
||||
def test_dynamic_values_are_escaped(screen):
|
||||
"""No field of a response reaches markup bare: every `${x.field}` sits inside esc()/dat()/enc().
|
||||
Counts (`.length`) are numbers; the api()/mutate() lines build URLs, where enc() is the rule."""
|
||||
Counts (`.length`) are numbers; the api()/mutate()/arbiter() lines build URLs, where enc() is the rule."""
|
||||
code = _text_builders(screen)
|
||||
assert "versionText = " not in code and "infoLines = " not in code
|
||||
code = "\n".join(line for line in code.splitlines() if not re.search(r"\b(?:api|mutate)[(]'", line))
|
||||
assert len(_interpolations(code)) > 50
|
||||
assert not _bare(code), _bare(code)
|
||||
|
||||
|
||||
def _bare(code: str) -> list[str]:
|
||||
"""The interpolations in `code` that render a response field without esc()/dat()/enc()."""
|
||||
code = "\n".join(line for line in code.splitlines() if not re.search(r"\b(?:api|mutate|arbiter)[(]'", line))
|
||||
exprs = _interpolations(code)
|
||||
assert len(exprs) > 50, len(exprs)
|
||||
bare = []
|
||||
for e in exprs:
|
||||
if _wrapped(e):
|
||||
@@ -190,7 +199,7 @@ def test_dynamic_values_are_escaped(screen):
|
||||
part = part.strip()
|
||||
if op not in ("?", "&&") and re.fullmatch(r"[a-z]\w*(?:\.\w+|\[\d+\])+", part) and not part.endswith(".length"):
|
||||
bare.append(e)
|
||||
assert not bare, bare
|
||||
return bare
|
||||
|
||||
|
||||
def _wrapped(e: str) -> bool:
|
||||
@@ -236,3 +245,295 @@ def test_it_is_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
|
||||
assert re.search(rf"""^ ['"]{re.escape(phrase)}['"]: """, block, re.M), f"no English for {phrase!r}"
|
||||
|
||||
|
||||
# ── the checking procedure's editor (Mapa / Standardy) ──────────────────────────────────────────
|
||||
# Arbiter is a sibling module on the same origin: the console reaches it through `arbiter()` only,
|
||||
# so these are the routes it may ask for (Task 6's trial and standards check included).
|
||||
ARBITER_ROUTES = {
|
||||
("POST", "skill-check/normalize"), ("GET", "skill-check/clause-types"),
|
||||
("POST", "skills/{}/versions/{}/sync"), ("GET", "skills/{}/versions/{}"),
|
||||
("POST", "agents/{}/trial"), ("POST", "agents/{}/standards-check"), ("GET", "agents/{}"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def plan_editor(console) -> str:
|
||||
return _section(console, "/* ── checking procedure", "/* ── import ──")
|
||||
|
||||
|
||||
def test_arbiter_calls_hit_only_known_routes(console, screen):
|
||||
calls = {(m.group(1), _path(_first_arg(console, m.end())))
|
||||
for m in re.finditer(r"\barbiter[(]'([A-Z]+)', ", console)}
|
||||
assert {("POST", "skill-check/normalize"), ("GET", "skill-check/clause-types")} <= calls, calls
|
||||
assert calls <= ARBITER_ROUTES, calls - ARBITER_ROUTES
|
||||
# One helper, same origin, the session cookie; never api()/mutate(), which are Atrium's own.
|
||||
helper = _section(console, "async function arbiter(", "\n}\n")
|
||||
assert "new URL('../arbiter/api/v1/' + path, document.baseURI)" in helper
|
||||
assert "credentials: 'same-origin'" in helper
|
||||
assert "async function arbiter(" not in screen # its '/api/v1' literal stays out of the screen
|
||||
assert not re.search(r"\b(?:api|mutate)[(]'[A-Z]+', '/?(?:skill-check|\.\./arbiter)", console)
|
||||
|
||||
|
||||
def test_the_editor_saves_with_file_updates_not_files(console, plan_editor):
|
||||
save = _section(console, "function savePlan(", "\n}\n")
|
||||
# Normalized by Arbiter first (its parser is the one that knows the format), then stored as ONE
|
||||
# file of a new version: the other files carry over on the server, the console never holds them.
|
||||
assert save.index("arbiter('POST', 'skill-check/normalize'") < save.index("/versions'")
|
||||
assert "file_updates: { 'sprawdzanie.yaml': utf8Base64(" in save
|
||||
assert not re.search(r"\bfiles:", save)
|
||||
assert "JSON.stringify({ wersja_formatu: 1, kroki: " in save
|
||||
# Ruling 15: the new version is made on the version the draft was loaded from, not on the
|
||||
# server's default base, which may be a newer proposal the draft never saw.
|
||||
assert "base_n: state._planBase.n, file_updates:" in save
|
||||
# The bytes are UTF-8 (TextEncoder), base64'd in slices: fromCharCode(...all) overflows the stack.
|
||||
enc_fn = _section(console, "function utf8Base64(", "\n}\n")
|
||||
assert "new TextEncoder().encode(" in enc_fn
|
||||
base = _section(console, "function bytesBase64(", "\n}\n")
|
||||
assert "0x8000" in base
|
||||
|
||||
|
||||
def test_the_draft_is_kept_until_saved_or_left_on_purpose(console, plan_editor):
|
||||
assert "state._plan" in plan_editor and "state._planDirty" in plan_editor
|
||||
route = _section(console, "async function router(", "\n}\n")
|
||||
assert "if (leavingDraft()) return;" in route
|
||||
assert "beforeunload" in console
|
||||
|
||||
|
||||
def test_the_draft_is_keyed_to_the_version_it_was_loaded_from(console, plan_editor):
|
||||
"""A draft belongs to one version (`state._planBase`), set where it is loaded and where a new
|
||||
procedure is started, and a re-render never shows it under another version."""
|
||||
load = _section(console, "async function loadPlan(", "\n}\n")
|
||||
assert "state._planBase = { id: shown.id, n: shown.n };" in load
|
||||
start = _section(console, "function startPlan(", "\n}\n")
|
||||
assert "state._planBase = { id: shown.id, n: shown.n };" in start
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "state._planBase.id !== shown.id" in view
|
||||
# "Nowa wersja" asks before it could leave a dirty draft behind.
|
||||
editor = _section(console, "function openSkillEditor(", "\n}\n")
|
||||
assert "if (id && state._planDirty) { askLeavingDraft(() => openSkillEditor(id)); return; }" in editor
|
||||
|
||||
|
||||
def test_plan_values_are_escaped(screen, plan_editor):
|
||||
"""`test_dynamic_values_are_escaped` reads the whole screen, the editor's lines included."""
|
||||
assert plan_editor in screen
|
||||
for fn in ("function planMapHtml(", "function planStandardsHtml(", "function openStepEditor(",
|
||||
"function openStandardEditor("):
|
||||
assert fn in plan_editor
|
||||
assert len(_interpolations(plan_editor)) > 20
|
||||
assert not _bare(plan_editor), _bare(plan_editor)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phrase", [
|
||||
"Opis", "Mapa", "Standardy", "Dodaj procedurę sprawdzania", "Niezapisane zmiany",
|
||||
"Zapisz jako nową wersję", "Odrzuć zmiany",
|
||||
"Nie masz dostępu do usługi sprawdzania. Poproś administratora o moduł Arbiter.",
|
||||
"Zapisano wersję {n} jako propozycję. Firma sprawdza wersją {m}, dopóki zatwierdzający jej nie zatwierdzi.",
|
||||
"Dodaj krok", "Edytuj krok", "Nowy krok", "Nazwa kroku", "Krok", "W górę", "W dół",
|
||||
"Dodaj standard", "Edytuj standard", "Nowy standard", "Zasada", "Brzmienie", "Odstępstwo", "Waga",
|
||||
"Typ klauzuli", "Przykłady testowe", "Dodaj przykład", "blokująca", "istotna", "informacyjna",
|
||||
"spełnia", "narusza", "Ten krok nie ma jeszcze standardów.", "Wczytywanie procedury…",
|
||||
"Masz niezapisane zmiany w procedurze sprawdzania.", "Wyjdź bez zapisywania", "Zostań",
|
||||
"Procedura sprawdzania w tej wersji ma błąd, więc formularze jej nie otworzą:",
|
||||
"Podaj nazwę kroku.", "Podaj zasadę.",
|
||||
# Task 6: the trial, the standards check and the approver's queue
|
||||
"Próba", "Zatwierdzona dla firmy", "Propozycja",
|
||||
"Próba sprawdza, czy wybrany model trafnie ocenia 15 umów wzorcowych. Test standardów sprawdza "
|
||||
"przykłady przypięte do Twoich standardów. Prawdziwe umowy sprawdza tylko wersja zatwierdzona dla "
|
||||
"firmy z ukończoną próbą.",
|
||||
"Próby jeszcze nie uruchomiono", "Uruchom próbę", "Zatrzymaj", "Sprawdź standardy", "Test standardów",
|
||||
"{k} z {of} umów, zgodność {a}/{r}", "Testu standardów jeszcze nie uruchomiono",
|
||||
"Sprawdzono przykładów: {k}", "Model ocenił wszystkie przykłady tak, jak oczekiwano.",
|
||||
"Model ocenił przykład inaczej, niż oczekiwano", "Model nie był pewny", "Brak przykładów testowych",
|
||||
"To podpowiedź. Nie blokuje zatwierdzenia.", "Do zatwierdzenia", "Próba: {k} z {of}, zgodność {a}/{r}",
|
||||
"Próby nie uruchomiono", "Brak danych o próbie", "Twój wniosek. Decyduje inny zatwierdzający.",
|
||||
# The final fix wave: the publish action on the version shown, an approver (not an
|
||||
# administrator) decides, and a trial step that never answers.
|
||||
"Wyślij do zatwierdzenia", "Wysłano do zatwierdzenia.", "Ta wersja czeka na zgodę zatwierdzającego.",
|
||||
"Ten krok trwa zbyt długo. Sprawdź serwer modelu i spróbuj ponownie.",
|
||||
])
|
||||
def test_new_phrases_are_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
|
||||
assert re.search(rf"""^ ['"]{re.escape(phrase)}['"]: """, block, re.M), f"no English for {phrase!r}"
|
||||
|
||||
|
||||
# ── a version's trial and standards check (Próba), and the approver's queue ─────────────────────
|
||||
def test_trial_loop_rereads_the_agent_on_504(console):
|
||||
"""Atrium's front door cuts a proxied request at 300 s with its own 504 while Arbiter finishes the
|
||||
step: the loop reads the agent until that step has landed, and only then asks for the next one,
|
||||
so no POST ever goes out beside a step still running. The behaviour is `trial_loop.mjs`'s."""
|
||||
loop = _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
assert "if (ex.status !== 504) throw ex;" in loop
|
||||
assert "const cut = await awaitCutStep(t, sync.agent_id, (a) => stepLanded(before, stored(a), count));" in loop
|
||||
# One capped retry, not a POST every 125 minutes for ever (behaviour: trial_loop.mjs).
|
||||
assert "if (capped) throw Object.assign(new Error(TRIAL_SLOW), { slow: true });" in loop
|
||||
assert "while (state._trials[t.version] === t && !t.stop)" in loop
|
||||
assert "Promise.all" not in loop
|
||||
# One loop at a time: a second press while one runs does nothing.
|
||||
assert "if (!t || t.running || t.loading) return;" in loop
|
||||
wait = _section(console, "async function awaitCutStep(", "\n}\n")
|
||||
assert "await arbiter('GET', 'agents/' + enc(agentId));" in wait
|
||||
assert "await sleep(TRIAL_POLL_MS);" in wait
|
||||
assert "Date.now() >= until" in wait
|
||||
assert "const TRIAL_WAIT_MS = 125 * 60 * 1000;" in console
|
||||
# Arbiter's "slot busy" carries no code; nothing here reads a refusal's words.
|
||||
assert "409" not in loop + wait and "busy" not in loop + wait
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_trial_loop_waits_for_the_cut_off_step_by_behaviour():
|
||||
"""`runVersionLoop` under a scripted arbiter(): a 504, a re-read with no progress, a re-read with
|
||||
progress, and only then the next POST, with no error; plus the cap, "Zatrzymaj" and sign-out,
|
||||
one capped retry at most, and a failed read during the wait that keeps the wait going."""
|
||||
r = subprocess.run(
|
||||
[NODE, str(ROOT / "backend" / "tests" / "js" / "trial_loop.mjs"), str(ROOT / "frontend" / "app.js")],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
assert r.returncode == 0, r.stdout + r.stderr
|
||||
|
||||
|
||||
def test_the_run_state_is_kept_per_version(console):
|
||||
"""A loop goes on while another version is shown; coming back finds its button still disabled,
|
||||
so a second press cannot post beside the step still running."""
|
||||
assert not re.search(r"state\._trial\b(?!s)", console)
|
||||
assert "_trials: {}," in _section(console, "const state = {", "\n};")
|
||||
assert "_trials" not in _section(console, "async function viewSkill(", "\n}\n")
|
||||
load = _section(console, "async function loadTrial(", "\n}\n")
|
||||
assert "if (state._trials[shown.id]) return;" in load
|
||||
assert "const t = state._trials[shown.id];" in _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
assert "const t = state._trials[shown.id] || { loading: true };" in _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
assert "state._trials = {};" in _section(console, "function showLogin(", "\n}\n")
|
||||
|
||||
|
||||
def test_the_approval_chip_reads_the_version_as_get_version_read_it(console):
|
||||
"""get_skill's `current` has no `approved_for_firm`; the default view shows the current version as
|
||||
get_version read it, so the firm's approved version is not labelled a proposal."""
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "|| (s.current && vs.find((v) => v.id === s.current.id)) || vs[0];" in view
|
||||
assert "|| s.current ||" not in view
|
||||
assert "shown.approved_for_firm" in _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
|
||||
|
||||
def test_trial_and_check_pass_agent_version_id(console):
|
||||
"""A skill's agent names the version to try: the sync freezes it first and gives its id."""
|
||||
steps = _section(console, "const VERSION_STEPS = {", "\n};")
|
||||
assert "arbiter('POST', `agents/${enc(agent)}/trial?agent_version_id=${enc(vid)}`)" in steps
|
||||
assert "arbiter('POST', `agents/${enc(agent)}/standards-check?agent_version_id=${enc(vid)}`)" in steps
|
||||
loop = _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
sync = loop.index("arbiter('POST', `skills/${enc(s.id)}/versions/${shown.n}/sync`)")
|
||||
assert sync < loop.index("VERSION_STEPS[kind](sync.agent_id, vid)")
|
||||
assert "const vid = sync.agent_version_id;" in loop
|
||||
load = _section(console, "async function loadTrial(", "\n}\n")
|
||||
assert "arbiter('GET', `skills/${enc(s.id)}/versions/${shown.n}`)" in load
|
||||
assert "ex.problem.code === 'not_synced'" in load
|
||||
|
||||
|
||||
def test_the_run_button_is_disabled_while_running(console):
|
||||
panel = _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
assert "const busy = !!(t.running || t.loading);" in panel
|
||||
assert "onclick=\"runVersionLoop('trial')\"${busy ? ' disabled' : ''}" in panel
|
||||
assert "onclick=\"runVersionLoop('check')\"${busy ? ' disabled' : ''}" in panel
|
||||
# "Zatrzymaj" ends the loop after the step under way: a flag the loop reads, not an abort.
|
||||
stop = _section(console, "function stopVersionLoop(", "\n}\n")
|
||||
assert "t.stop = true;" in stop
|
||||
assert "abort" not in stop
|
||||
|
||||
|
||||
def test_approver_tab_shows_only_with_permission(console):
|
||||
"""The approver's queue under Skille i agenci follows `/skills/permissions`, not is_admin."""
|
||||
tabs = _section(console, "function skillTabs(", "\n}\n")
|
||||
assert "(state._skillPerms || {}).approve ? tab('requests', '#/skills/requests', 'Do zatwierdzenia') : ''" in tabs
|
||||
assert "isAdmin" not in tabs
|
||||
assert "api('GET', '/skills/permissions')" in _section(console, "async function viewSkills(", "\n}\n")
|
||||
view = _section(console, "async function viewSkillRequests(", "\n}\n")
|
||||
assert "state._skillPerms = await api('GET', '/skills/permissions');" in view
|
||||
assert view.index("if (!state._skillPerms.approve)") < view.index("api('GET', '/admin/publish-requests')")
|
||||
assert "isAdmin" not in view
|
||||
route = _section(console, "async function router(", "\n}\n")
|
||||
here = route.index("else if (seg[0] === 'skills' && seg[1] === 'requests') await viewSkillRequests(C);")
|
||||
assert here < route.index("else if (seg[0] === 'skills') await viewSkills(")
|
||||
# One card renderer for both queues; the administrator's route stays.
|
||||
assert "publishRequestCards(rows, { trials })" in view
|
||||
assert "publishRequestCards(rows)" in _section(console, "async function viewAdminPublishRequests(", "\n}\n")
|
||||
# A trial line only for a checking skill, from Arbiter's read; any refusal is "no data".
|
||||
line = _section(console, "async function requestTrialLine(", "\n}\n")
|
||||
assert "arbiter('GET', `skills/${enc(r.item.id)}/versions/${r.version.n}`)" in line
|
||||
assert "'Brak danych o próbie'" in line
|
||||
|
||||
|
||||
|
||||
# ── the final fix wave: publish and save act on the version shown; four eyes on the author ──────
|
||||
def test_the_publish_action_names_the_version_shown(console):
|
||||
"""The button publishes the version on screen (`?n=`): without `n` the server takes the actor's
|
||||
own newest version, so a proposer had no way to put a proposal forward and an editor published
|
||||
something other than what they were looking at."""
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "const publishing = publishAction(s, shown);" in view
|
||||
assert "onclick=\"publishSkill('${esc(s.id)}', ${esc(String(shown.n))})\"><span>${esc(publishing)}</span>" in view
|
||||
assert "publishable" not in view
|
||||
publish = _section(console, "function publishSkill(", "\n}\n")
|
||||
assert "mutate('POST', `/skills/${enc(id)}/publish?n=${enc(String(n))}`, undefined, {" in publish
|
||||
assert "'Wysłano do zatwierdzenia.'" in publish
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_publish_action_follows_who_may_put_the_version_forward(console):
|
||||
"""Ruling 12: an editor may publish any version newer than the firm's current one; anybody else
|
||||
only a version they wrote, and theirs goes to the approvers. Nothing on an archived skill."""
|
||||
fn = "function publishAction(" + _section(console, "function publishAction(", "\n}\n") + "\n}\n"
|
||||
cur = {"id": "cur", "n": 3, "created_by": "me"}
|
||||
firm = {"scope": "firm", "status": "active", "current_version_id": "cur", "current": cur}
|
||||
editor = {**firm, "proposable": True, "editable": True}
|
||||
proposer = {**firm, "proposable": True, "editable": False}
|
||||
newer = {"id": "p", "n": 4}
|
||||
cases = [
|
||||
(editor, {**newer, "created_by": "x"}, "Opublikuj w firmie"),
|
||||
(editor, cur, None),
|
||||
# An older version would roll the firm back; an approver is refused it anyway.
|
||||
(editor, {"id": "old", "n": 2, "created_by": "me"}, None),
|
||||
(proposer, {**newer, "created_by": "me"}, "Wyślij do zatwierdzenia"),
|
||||
(proposer, cur, None),
|
||||
(proposer, {**newer, "created_by": "x"}, None),
|
||||
({**editor, "status": "archived"}, {**newer, "created_by": "me"}, None),
|
||||
({**firm, "proposable": False, "editable": False}, {**newer, "created_by": "me"}, None),
|
||||
# A personal skill's current version is what its owner puts forward to the firm, and a
|
||||
# firm skill whose first publication still waits has no current one to measure against.
|
||||
({"scope": "personal", "status": "active", "current_version_id": "cur", "current": cur,
|
||||
"proposable": True, "editable": True}, cur, "Opublikuj w firmie"),
|
||||
({**editor, "current_version_id": None, "current": None}, {**newer, "created_by": "me"},
|
||||
"Opublikuj w firmie"),
|
||||
(editor, None, None),
|
||||
]
|
||||
script = (fn + "const state = { user: { id: 'me' } };\n"
|
||||
+ f"process.stdout.write(JSON.stringify({json.dumps([[s, v] for s, v, _ in cases])}"
|
||||
+ ".map(([s, v]) => publishAction(s, v))));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert json.loads(r.stdout) == [want for _, _, want in cases]
|
||||
|
||||
|
||||
def test_a_new_version_is_made_on_the_version_shown(console):
|
||||
"""Ruling 15 for "Nowa wersja" too: the form shows the version on screen and the save names it as
|
||||
`base_n`, so its text and the files the server carries over come from one version."""
|
||||
editor = _section(console, "function openSkillEditor(", "\n}\n")
|
||||
assert "const v = id ? state._skillView.shown : null;" in editor
|
||||
assert "const save = id ? `'${esc(id)}', ${v ? esc(String(v.n)) : 'null'}` : '';" in editor
|
||||
assert "onclick=\"saveSkill(${save})\"" in editor
|
||||
save = _section(console, "function saveSkill(", "\n}\n")
|
||||
assert "function saveSkill(id, baseN) {" in console
|
||||
assert "if (baseN) body.base_n = baseN;" in save
|
||||
assert "_skillLatest" not in console
|
||||
|
||||
|
||||
def test_an_approver_gets_no_buttons_on_a_version_they_wrote(console):
|
||||
"""The server refuses a non-administrator who filed the request or wrote the version; the card
|
||||
says so instead of offering buttons that would fail."""
|
||||
cards = _section(console, "function publishRequestCards(", "\n}\n")
|
||||
assert ("!isAdmin() && (r.requested_by.id === state.user.id || r.version.created_by === state.user.id)"
|
||||
in cards)
|
||||
|
||||
|
||||
def test_the_approver_not_the_administrator_decides_in_the_copy(screen):
|
||||
assert "Wysłano do zatwierdzenia przez administratora." not in screen
|
||||
assert "czeka na zgodę administratora" not in screen
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. Who sees what is decided in
|
||||
`services/skills.py` (skills are not org-tree nodes), so this suite pins that rule end to end: the
|
||||
visibility matrix, a firm skill's next version staying invisible until an administrator approves
|
||||
visibility matrix, a firm skill's next version not becoming current until an approver approves
|
||||
it, the `skills_firm_publish` switch, and the audit rows every write leaves. Then agents (a firm
|
||||
agent never pins a personal skill), T2 on export (`skills_firm_export`, for a skill and for an agent
|
||||
with everything it pins), import round trips keeping one content sum, a malicious pack answered as
|
||||
@@ -109,21 +109,78 @@ def test_a_firm_skill_is_everybodys_to_read(admin_client, client, owner, other,
|
||||
assert r.json()["current"]["n"] == 1
|
||||
assert any(s["id"] == sid for s in api.get(SKILLS, headers=who).json())
|
||||
|
||||
# Reading is not changing: anybody else may not touch it.
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Hijacked\n"},
|
||||
headers=bearer(other["token"]))
|
||||
assert r.status_code == 403, r.text
|
||||
# Archiving stays with the editors; a new version from anybody else is a proposal (below).
|
||||
assert client.post(f"{SKILLS}/{sid}/archive",
|
||||
headers=bearer(other["token"])).status_code == 403
|
||||
|
||||
|
||||
def test_other_user_proposes_on_a_firm_skill(admin_client, client, owner, other, firm_skill):
|
||||
"""A proposal is a new version; it never moves the firm's current one, and a proposer's own
|
||||
publish is a request even where the firm publishes directly."""
|
||||
sid, me = firm_skill["id"], bearer(other["token"])
|
||||
with settings_set(admin_client, skills_firm_publish="direct"):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Proposal\n"}, headers=me)
|
||||
assert r.status_code == 201, r.text
|
||||
n = r.json()["n"]
|
||||
seen = client.get(f"{SKILLS}/{sid}", headers=me).json()
|
||||
assert seen["current"]["n"] == n - 1 and n in [v["n"] for v in seen["versions"]]
|
||||
assert (seen["editable"], seen["proposable"]) == (False, True)
|
||||
both = client.post(f"{SKILLS}/{sid}/versions", headers=me,
|
||||
json={"files": {}, "file_updates": {"a.md": "eA=="}})
|
||||
assert both.status_code == 422, both.text
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", params={"n": n}, headers=me)
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=me).json()["current"]["n"] == n - 1
|
||||
_approve(admin_client, sid)
|
||||
|
||||
|
||||
def skill_v1(client, owner, sid) -> dict:
|
||||
return client.get(f"{SKILLS}/{sid}/versions/1", headers=bearer(owner["token"])).json()
|
||||
|
||||
|
||||
def test_base_n_builds_on_the_version_shown(admin_client, client, owner, other):
|
||||
"""Ruling 15: a save names the version it was made on. A proposer looking at the firm's current
|
||||
version builds on it, not on their own newer proposal; a version they cannot read is a 404."""
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]), body="# Approved\n")
|
||||
sid = skill["id"]
|
||||
assert client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"])).status_code == 200
|
||||
_approve(admin_client, sid)
|
||||
me = bearer(other["token"])
|
||||
mine = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Mine\n"}, headers=me)
|
||||
assert mine.status_code == 201 and mine.json()["n"] == 2, mine.text
|
||||
|
||||
# Without base_n the default stays (Ruling 9): the proposer's own newest version.
|
||||
default = client.post(f"{SKILLS}/{sid}/versions", json={"description": "Next."}, headers=me)
|
||||
assert default.status_code == 201 and default.json()["body"] == "# Mine\n", default.text
|
||||
|
||||
shown = client.post(f"{SKILLS}/{sid}/versions", headers=me,
|
||||
json={"base_n": 1, "file_updates": {"sprawdzanie.yaml": "eA=="}})
|
||||
assert shown.status_code == 201, shown.text
|
||||
assert shown.json()["n"] == 4 and shown.json()["body"] == "# Approved\n"
|
||||
assert shown.json()["description"] == skill_v1(client, owner, sid)["description"]
|
||||
assert [f["path"] for f in shown.json()["files"]] == ["sprawdzanie.yaml"]
|
||||
|
||||
owners = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Owner draft\n"},
|
||||
headers=bearer(owner["token"]))
|
||||
assert owners.status_code == 201, owners.text
|
||||
before = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
|
||||
for n in (owners.json()["n"], 99):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"base_n": n, "body": "# x\n"}, headers=me)
|
||||
assert r.status_code == 404, (n, r.text)
|
||||
after = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_a_missing_skill_is_404(client, owner):
|
||||
assert client.get(f"{SKILLS}/{uuid.uuid4()}", headers=bearer(owner["token"])).status_code == 404
|
||||
|
||||
|
||||
# ── publication ───────────────────────────────────────────────────────────────
|
||||
def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client, owner, other,
|
||||
def test_a_new_firm_version_is_not_current_until_approved(admin_client, client, owner, other,
|
||||
firm_skill):
|
||||
"""Written is not published: until an approver says yes the firm's current version stays, and
|
||||
the new one is open to its editors only (Ruling 8); approved, it is the current one for all."""
|
||||
sid = firm_skill["id"]
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# NDA v2\n\nNew rule.\n"},
|
||||
@@ -135,8 +192,9 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
|
||||
out = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
|
||||
return out["current"]["n"], [v["n"] for v in out["versions"]]
|
||||
|
||||
# Written is not published: everybody else still reads the approved version, only.
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
# Written is not published: somebody else's proposal (or the owner's) stays closed to
|
||||
# everybody who did not write it and cannot edit.
|
||||
assert seen_by_other()[0] == n - 1 and n not in seen_by_other()[1]
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/{n}",
|
||||
headers=bearer(other["token"])).status_code == 404
|
||||
owner_view = client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()
|
||||
@@ -146,7 +204,7 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
again = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
assert again.status_code == 409 # already waiting
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
assert seen_by_other()[0] == n - 1 and n not in seen_by_other()[1]
|
||||
|
||||
# The administrator's queue shows both sides of the diff.
|
||||
request = next(q for q in admin_client.get(REQUESTS).json() if q["item"]["id"] == sid)
|
||||
@@ -155,7 +213,7 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
|
||||
|
||||
decided = _approve(admin_client, sid)
|
||||
assert decided["status"] == "approved"
|
||||
assert seen_by_other() == (n, [n])
|
||||
assert seen_by_other()[0] == n and n in seen_by_other()[1]
|
||||
assert admin_client.post(f"{REQUESTS}/{request['id']}/approve").status_code == 409
|
||||
|
||||
|
||||
@@ -198,6 +256,143 @@ def test_direct_publication_is_the_administrators_switch(admin_client, client, o
|
||||
assert _audit(admin_client, "skill.publish_request", sid) == []
|
||||
|
||||
|
||||
# ── the firm's approver ───────────────────────────────────────────────────────
|
||||
def _workspace_id(admin_client) -> str:
|
||||
return next(u["id"] for u in admin_client.get("/api/v1/tree/containers").json()
|
||||
if u["kind"] == "workspace")
|
||||
|
||||
|
||||
def _grant(admin_client, node_id: str, person: dict, role: str) -> None:
|
||||
r = admin_client.put(f"/api/v1/nodes/{node_id}/grants",
|
||||
json={"user_id": person["id"], "role": role})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def _pending_request(admin_client, client, author: dict, **over) -> tuple[dict, str]:
|
||||
"""A personal skill of `author` waiting for approval -> (skill, request id)."""
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(author["token"]), **over)
|
||||
r = client.post(f"{SKILLS}/{skill['id']}/publish", headers=bearer(author["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
return skill, r.json()["request_id"]
|
||||
|
||||
|
||||
def test_an_approver_on_the_workspace_decides(admin_client, client, make_user, owner, other):
|
||||
approver = make_user("skills-approver")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
assert client.get(f"{SKILLS}/permissions", headers=head).json() == {"approve": True}
|
||||
assert client.get(f"{SKILLS}/permissions", headers=bearer(other["token"])).json() == {
|
||||
"approve": False}
|
||||
|
||||
skill, request_id = _pending_request(admin_client, client, owner)
|
||||
sid = skill["id"]
|
||||
# The approver is not an administrator and the skill is somebody's personal one, yet the
|
||||
# queue shows it and the version can be read: they cannot judge what they cannot open.
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=head).status_code == 404
|
||||
queue = client.get(REQUESTS, headers=head)
|
||||
assert queue.status_code == 200 and any(q["id"] == request_id for q in queue.json())
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 200
|
||||
|
||||
r = client.post(f"{REQUESTS}/{request_id}/approve", headers=head)
|
||||
assert r.status_code == 200 and r.json()["status"] == "approved", r.text
|
||||
firm = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
|
||||
assert firm["scope"] == "firm" and firm["current"]["n"] == 1
|
||||
assert firm["current_version_id"] == firm["current"]["id"]
|
||||
|
||||
|
||||
def test_a_decided_request_opens_nothing_more_to_an_approver(admin_client, client, make_user,
|
||||
owner):
|
||||
approver = make_user("skills-approver-2")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
skill, request_id = _pending_request(admin_client, client, owner)
|
||||
sid = skill["id"]
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 200
|
||||
r = client.post(f"{REQUESTS}/{request_id}/decline", headers=head)
|
||||
assert r.status_code == 200 and r.json()["status"] == "declined", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 404
|
||||
|
||||
|
||||
def test_an_approver_on_a_group_only_may_not(admin_client, client, make_user, owner):
|
||||
person = make_user("skills-group-approver")
|
||||
group = admin_client.post("/api/v1/nodes", json={
|
||||
"kind": "group", "name": f"Skills {RUN}-{uuid.uuid4().hex[:4]}",
|
||||
"parent_id": _workspace_id(admin_client)}).json()
|
||||
_grant(admin_client, group["id"], person, "approver")
|
||||
head = bearer(person["token"])
|
||||
_, request_id = _pending_request(admin_client, client, owner)
|
||||
assert client.get(f"{SKILLS}/permissions", headers=head).json() == {"approve": False}
|
||||
assert client.get(REQUESTS, headers=head).status_code == 403
|
||||
assert client.post(f"{REQUESTS}/{request_id}/approve", headers=head).status_code == 403
|
||||
|
||||
|
||||
def test_an_editor_may_not(admin_client, client, make_user, owner):
|
||||
person = make_user("skills-editor")
|
||||
_grant(admin_client, _workspace_id(admin_client), person, "editor")
|
||||
head = bearer(person["token"])
|
||||
_, request_id = _pending_request(admin_client, client, owner)
|
||||
assert client.get(REQUESTS, headers=head).status_code == 403
|
||||
assert client.post(f"{REQUESTS}/{request_id}/approve", headers=head).status_code == 403
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_their_own_request(admin_client, client, make_user):
|
||||
approver = make_user("skills-approver-3")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
skill, request_id = _pending_request(admin_client, client, approver)
|
||||
for verb in ("approve", "decline"):
|
||||
r = client.post(f"{REQUESTS}/{request_id}/{verb}", headers=head)
|
||||
assert r.status_code == 403 and "cannot decide your own request" in r.text, r.text
|
||||
# An administrator may, whoever filed it.
|
||||
assert admin_client.post(f"{REQUESTS}/{request_id}/approve").status_code == 200
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_a_request_for_a_version_they_wrote(admin_client, client,
|
||||
make_user, owner):
|
||||
"""Four eyes on the author too: the owner puts forward an approver's proposal (an editor's
|
||||
publish of a non-editor's version is a request, Ruling 10); its author may not decide it,
|
||||
another approver may."""
|
||||
author, second = make_user("skills-approver-author"), make_user("skills-approver-second")
|
||||
for person in (author, second):
|
||||
_grant(admin_client, _workspace_id(admin_client), person, "approver")
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
assert client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"])).status_code == 200
|
||||
_approve(admin_client, sid)
|
||||
proposal = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# The approver's idea\n"},
|
||||
headers=bearer(author["token"]))
|
||||
assert proposal.status_code == 201, proposal.text
|
||||
n = proposal.json()["n"]
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", params={"n": n}, headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
request_id = r.json()["request_id"]
|
||||
|
||||
for verb in ("approve", "decline"):
|
||||
r = client.post(f"{REQUESTS}/{request_id}/{verb}", headers=bearer(author["token"]))
|
||||
assert r.status_code == 403 and "cannot decide your own request" in r.text, r.text
|
||||
r = client.post(f"{REQUESTS}/{request_id}/approve", headers=bearer(second["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "approved", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["current"]["n"] == n
|
||||
|
||||
|
||||
def test_only_an_approver_reads_a_version_waiting_in_a_request(admin_client, client, make_user,
|
||||
owner):
|
||||
"""The approver's read exception is the widest new read path: a version waiting in a request on
|
||||
somebody's PERSONAL skill opens, version and file alike, to an approver and to nobody else."""
|
||||
approver, plain = make_user("skills-approver-reader"), make_user("skills-plain")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
# "# Zasady\n", base64.
|
||||
skill, _ = _pending_request(admin_client, client, owner, files={"zasady.md": "IyBaYXNhZHkK"})
|
||||
version = f"{SKILLS}/{skill['id']}/versions/1"
|
||||
for path in (version, f"{version}/files/zasady.md"):
|
||||
r = client.get(path, headers=bearer(plain["token"]))
|
||||
assert r.status_code == 404, (path, r.text)
|
||||
r = client.get(path, headers=bearer(approver["token"]))
|
||||
assert r.status_code == 200, (path, r.text)
|
||||
|
||||
|
||||
# ── the audit ─────────────────────────────────────────────────────────────────
|
||||
def test_every_write_leaves_one_audit_row(admin_client, client, owner):
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import uuid
|
||||
import zipfile
|
||||
@@ -8,8 +9,9 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.enums import NodeRole
|
||||
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Skill
|
||||
from app.models import AppUser, Skill, SkillFile
|
||||
from app.services import skill_pack, skills
|
||||
from app.services.skill_pack import PackRejected
|
||||
|
||||
@@ -52,17 +54,257 @@ def test_someone_elses_personal_skill_is_a_404_not_a_403():
|
||||
skills.archive_skill(db, user, db.skill.id, ip=None)
|
||||
|
||||
|
||||
def test_a_firm_skill_is_changed_only_by_its_editors():
|
||||
def test_a_firm_skill_is_archived_only_by_its_editors():
|
||||
db = _Db(_skill("firm"))
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
|
||||
skills.archive_skill(db, OTHER, db.skill.id, ip=None)
|
||||
|
||||
|
||||
def test_a_non_editor_reads_only_the_current_version():
|
||||
approved, pending = uuid.uuid4(), uuid.uuid4()
|
||||
skill = _skill("firm", current=approved)
|
||||
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
|
||||
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
|
||||
def _ver(creator, n):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n, created_by=creator.id, description="Opis",
|
||||
body_md="Treść", license="MIT", meta={})
|
||||
|
||||
|
||||
def test_an_editor_reads_every_firm_version():
|
||||
v1, v2 = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
assert skills.readable_version_ids(OWNER, skill, [v1, v2]) == {v1.id, v2.id}
|
||||
assert skills.readable_version_ids(ADMIN, skill, [v1, v2]) == {v1.id, v2.id}
|
||||
|
||||
|
||||
def test_a_proposer_reads_the_current_version_and_their_own_only():
|
||||
draft, current, mine, theirs = _ver(OWNER, 1), _ver(OWNER, 2), _ver(OTHER, 3), _ver(ADMIN, 4)
|
||||
skill = _skill("firm", current=current.id)
|
||||
# The owner's earlier personal draft (1) and somebody else's proposal (4) stay closed.
|
||||
assert skills.readable_version_ids(OTHER, skill, [draft, current, mine, theirs]) == {
|
||||
current.id, mine.id}
|
||||
|
||||
|
||||
class _VersionDb:
|
||||
"""What `new_version` and `publish_skill` touch. A select is answered by what it filters on
|
||||
(read off its bound parameters): `created_by` narrows to that author, a file query names its
|
||||
version; whatever is added is what a new version stored."""
|
||||
|
||||
def __init__(self, skill, versions, files=None):
|
||||
self.skill, self.versions, self.files = skill, list(versions), files or {}
|
||||
self.users = {u.id: u for u in (OWNER, OTHER, ADMIN)}
|
||||
self.added, self.params = [], []
|
||||
|
||||
def get(self, model, key):
|
||||
if model is Skill:
|
||||
return self.skill
|
||||
if model is AppUser:
|
||||
return self.users.get(key)
|
||||
return next((v for v in self.versions if v.id == key), None)
|
||||
|
||||
def scalar(self, stmt):
|
||||
params = stmt.compile().params
|
||||
self.params.append(params)
|
||||
if "kind_1" in params:
|
||||
return None # the pending-request lookup: nothing waits yet
|
||||
found = self.versions
|
||||
if "created_by_1" in params:
|
||||
found = [v for v in found if v.created_by == params["created_by_1"]]
|
||||
if "n_1" in params:
|
||||
found = [v for v in found if v.n == params["n_1"]]
|
||||
return max(found, key=lambda v: v.n, default=None)
|
||||
|
||||
def scalars(self, stmt):
|
||||
wanted = next((v for v in stmt.compile().params.values() if v in self.files), None)
|
||||
if wanted is not None:
|
||||
return iter(self.files[wanted])
|
||||
return iter(a for a in self.added if isinstance(a, SkillFile))
|
||||
|
||||
def add(self, row):
|
||||
self.added.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def _stored(path, data):
|
||||
return SimpleNamespace(path=path, content=data)
|
||||
|
||||
|
||||
def _sha(out):
|
||||
return {f["path"]: f["sha256"] for f in out["files"]}
|
||||
|
||||
|
||||
def _h(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def test_anyone_proposes_on_a_firm_skill_without_moving_current(audited):
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
out = skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id, {"body": "Nowa"}, ip=None)
|
||||
assert out["n"] == 2 and skill.current_version_id == v1.id
|
||||
assert audited == ["skill.version"]
|
||||
|
||||
|
||||
def test_a_proposal_does_not_rename_a_firm_skill(audited):
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id, {"name": "Hijacked"}, ip=None)
|
||||
assert skill.name == "NDA"
|
||||
|
||||
|
||||
def test_nobody_proposes_on_someone_elses_personal_skill():
|
||||
db = _VersionDb(_skill("personal"), [_ver(OWNER, 1)])
|
||||
for user in (OTHER, ADMIN):
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.new_version(db, user, db.skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def test_an_archived_firm_skill_takes_no_proposal():
|
||||
skill = _skill("firm")
|
||||
skill.status = "archived"
|
||||
assert not skills.can_propose(OTHER, skill)
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.new_version(_VersionDb(skill, [_ver(OWNER, 1)]), OTHER, skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def test_file_updates_keep_the_other_files_byte_identical(audited):
|
||||
note, old_yaml = "Notatka\n".encode(), b"wersja_formatu: 1\n"
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
db = _VersionDb(skill, [v1], {v1.id: [_stored("notatka.md", note),
|
||||
_stored("sprawdzanie.yaml", old_yaml)]})
|
||||
new_yaml = b"wersja_formatu: 1\nkroki: []\n"
|
||||
out = skills.new_version(db, OTHER, skill.id, {"file_updates": {"sprawdzanie.yaml": new_yaml}},
|
||||
ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(note), "sprawdzanie.yaml": _h(new_yaml)}
|
||||
|
||||
|
||||
def test_an_editors_save_does_not_inherit_a_strangers_proposal(audited):
|
||||
approved, proposal = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, proposal], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
proposal.id: [_stored("notatka.md", b"proposal"), _stored("extra.md", b"sneaky")]})
|
||||
out = skills.new_version(db, OWNER, skill.id, {"file_updates": {"b.md": b"b"}}, ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_a_proposers_second_save_builds_on_their_first(audited):
|
||||
approved, first = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, first], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
first.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {"file_updates": {"b.md": b"b"}}, ip=None)
|
||||
assert out["n"] == 3 and _sha(out) == {"notatka.md": _h(b"mine"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_a_proposers_save_after_a_newer_approval_builds_on_the_approved_one(audited):
|
||||
first, approved = _ver(OTHER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [first, approved], {
|
||||
first.id: [_stored("notatka.md", b"old mine")],
|
||||
approved.id: [_stored("notatka.md", b"approved")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {}, ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved")}
|
||||
|
||||
|
||||
def test_base_n_builds_on_the_version_shown_even_over_a_newer_own_proposal(audited):
|
||||
"""Ruling 15: the editor saves on top of the version the person was looking at. Without
|
||||
`base_n` this save would take the proposer's own v2 as its base and silently revert it."""
|
||||
approved, mine = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, mine], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
mine.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id,
|
||||
{"base_n": 1, "file_updates": {"sprawdzanie.yaml": b"y"}}, ip=None)
|
||||
assert out["n"] == 3
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved"), "sprawdzanie.yaml": _h(b"y")}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_n", [2, 9])
|
||||
def test_base_n_on_a_version_the_actor_cannot_read_is_a_404_and_adds_nothing(base_n):
|
||||
"""v2 is the owner's unpublished version of a firm skill: a proposer may not read it, so they
|
||||
may not build on it either (9: no such version). Same 404 as reading it."""
|
||||
approved, owners_draft = _ver(OWNER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, owners_draft])
|
||||
with pytest.raises(NotFoundError) as err:
|
||||
skills.new_version(db, OTHER, skill.id, {"base_n": base_n, "file_updates": {"a.md": b"x"}},
|
||||
ip=None)
|
||||
assert str(err.value) == "Version not found."
|
||||
assert db.added == []
|
||||
|
||||
|
||||
def test_an_absent_base_n_keeps_the_default_base(audited):
|
||||
"""`base_n: None` is what the router passes when the field is left out: Ruling 9 applies."""
|
||||
approved, first = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, first], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
first.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {"base_n": None, "file_updates": {"b.md": b"b"}},
|
||||
ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"mine"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_files_and_file_updates_together_are_refused():
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
with pytest.raises(ValidationError) as err:
|
||||
skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id,
|
||||
{"files": {}, "file_updates": {"a.md": b"x"}}, ip=None)
|
||||
assert str(err.value) == "Send files or file_updates, not both."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def direct(monkeypatch):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
|
||||
|
||||
|
||||
def test_a_proposers_publish_is_a_request_even_when_direct(direct, audited):
|
||||
approved, mine = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, mine]), OTHER, skill.id, 2, ip=None)
|
||||
assert out["status"] == "pending" and skill.current_version_id == approved.id
|
||||
assert audited == ["skill.publish_request"]
|
||||
|
||||
|
||||
def test_a_non_editor_cannot_publish_a_version_they_did_not_write(direct, audited):
|
||||
draft, current = _ver(OWNER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=current.id)
|
||||
db = _VersionDb(skill, [draft, current])
|
||||
for n in (1, 2, 9):
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.publish_skill(db, OTHER, skill.id, n, ip=None)
|
||||
assert not db.added and audited == []
|
||||
|
||||
|
||||
def test_an_editors_publish_of_their_own_version_stays_direct(direct, audited):
|
||||
approved, mine = _ver(OWNER, 1), _ver(ADMIN, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, mine]), ADMIN, skill.id, 2, ip=None)
|
||||
assert out["status"] == "published" and skill.current_version_id == mine.id
|
||||
|
||||
|
||||
def test_an_editor_publishing_a_proposal_files_a_request_even_when_direct(direct, audited):
|
||||
approved, proposal = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, proposal]), OWNER, skill.id, 2, ip=None)
|
||||
assert out["status"] == "pending" and skill.current_version_id == approved.id
|
||||
|
||||
|
||||
def test_publish_without_n_picks_the_actors_own_newest_version(direct, audited):
|
||||
approved, proposal, own = _ver(OWNER, 1), _ver(OTHER, 2), _ver(OWNER, 3)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, proposal, own, _ver(OTHER, 4)])
|
||||
out = skills.publish_skill(db, OWNER, skill.id, ip=None)
|
||||
assert out["status"] == "published" and skill.current_version_id == own.id
|
||||
|
||||
|
||||
def test_skill_out_says_who_may_propose():
|
||||
firm = _skill("firm")
|
||||
assert skills.skill_out(OTHER, firm)["proposable"] is True
|
||||
assert skills.skill_out(OTHER, firm)["editable"] is False
|
||||
assert skills.skill_out(OTHER, _skill("personal"))["proposable"] is False
|
||||
|
||||
|
||||
def test_next_n():
|
||||
@@ -126,8 +368,8 @@ def audited(monkeypatch):
|
||||
return actions
|
||||
|
||||
|
||||
def _version(n=1):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n)
|
||||
def _version(n=1, by=OWNER):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n, created_by=by.id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["approval", "direct"])
|
||||
@@ -168,13 +410,122 @@ def test_approving_an_older_version_is_refused():
|
||||
assert not skills.refuses_older(_skill("personal"), None, _version(1))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call", [
|
||||
lambda: skills.decide_publish(None, OTHER, uuid.uuid4(), approve=True),
|
||||
lambda: skills.pending_publish_requests(None, OTHER),
|
||||
class _ApproverDb:
|
||||
"""What `may_approve` and `decide_publish` touch: the workspace nodes, the locked request, the
|
||||
item and its versions. `roles` maps a node to the role the resolver would give this person."""
|
||||
|
||||
def __init__(self, nodes=(), request=None, item=None, version=None):
|
||||
self.nodes, self.request, self.item, self.version = list(nodes), request, item, version
|
||||
self.added = []
|
||||
|
||||
def scalars(self, _stmt):
|
||||
return iter(self.nodes)
|
||||
|
||||
def scalar(self, _stmt):
|
||||
return self.request
|
||||
|
||||
def get(self, model, _id):
|
||||
return self.version if model is skills.SkillVersion else self.item
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def _roles(monkeypatch, granted):
|
||||
"""The resolver answers `granted` for the node named in it, nothing elsewhere."""
|
||||
monkeypatch.setattr(skills.authz, "effective_role",
|
||||
lambda _db, _user, node: granted.get(node.name))
|
||||
|
||||
|
||||
# `_ReadDb.scalars` serves nodes and files alike, so the node also looks like a file row.
|
||||
WORKSPACE = SimpleNamespace(name="firm", kind="workspace", path="p", media_type="t", size=1,
|
||||
sha256="0" * 64)
|
||||
GROUP = SimpleNamespace(name="legal", kind="group")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("granted, allowed", [
|
||||
({"firm": NodeRole.approver}, True), # the role the firm's workspace gives
|
||||
({"firm": NodeRole.manager}, True), # and anything above it
|
||||
({"firm": NodeRole.editor}, False), # an editor writes, never decides
|
||||
({"firm": NodeRole.viewer}, False),
|
||||
({}, False),
|
||||
])
|
||||
def test_only_an_administrator_decides(call):
|
||||
def test_an_approver_on_the_workspace_decides(monkeypatch, granted, allowed):
|
||||
_roles(monkeypatch, granted)
|
||||
assert skills.may_approve(_ApproverDb([WORKSPACE]), OTHER) is allowed
|
||||
|
||||
|
||||
def test_an_approver_on_a_group_only_may_not(monkeypatch):
|
||||
# The query asks for workspace nodes only, so a role that exists on a group never gets asked.
|
||||
_roles(monkeypatch, {"legal": NodeRole.approver})
|
||||
assert skills.may_approve(_ApproverDb([WORKSPACE]), OTHER) is False
|
||||
with pytest.raises(AuthorizationError):
|
||||
call()
|
||||
skills.decide_publish(_ApproverDb([WORKSPACE]), OTHER, uuid.uuid4(), approve=True)
|
||||
|
||||
|
||||
def test_an_editor_may_not(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.editor})
|
||||
for call in (lambda db: skills.decide_publish(db, OTHER, uuid.uuid4(), approve=True),
|
||||
lambda db: skills.pending_publish_requests(db, OTHER)):
|
||||
with pytest.raises(AuthorizationError):
|
||||
call(_ApproverDb([WORKSPACE]))
|
||||
|
||||
|
||||
def test_an_administrator_needs_no_grant():
|
||||
assert skills.may_approve(_ApproverDb(), ADMIN) is True
|
||||
|
||||
|
||||
def _request(requested_by):
|
||||
return SimpleNamespace(id=uuid.uuid4(), kind="skill", status="pending", version_id=uuid.uuid4(),
|
||||
requested_by=requested_by.id, decided_by=None, decided_at=None,
|
||||
note=None)
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_their_own_request(monkeypatch, audited):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
req = _request(OTHER)
|
||||
db = _ApproverDb([WORKSPACE], request=req)
|
||||
with pytest.raises(AuthorizationError, match="You cannot decide your own request."):
|
||||
skills.decide_publish(db, OTHER, req.id, approve=True)
|
||||
assert req.status == "pending" and not audited
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_a_request_for_a_version_they_wrote(monkeypatch, audited):
|
||||
"""Four eyes on the author as well: an editor's publish of an approver's proposal is a request
|
||||
(Ruling 10), and the approver who wrote that version is not the second pair of eyes on it."""
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
version = _version(2, by=OTHER)
|
||||
skill = _skill("firm")
|
||||
req = _request(OWNER)
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb([WORKSPACE], request=req, item=skill, version=version)
|
||||
for approve in (True, False):
|
||||
with pytest.raises(AuthorizationError, match="You cannot decide your own request."):
|
||||
skills.decide_publish(db, OTHER, req.id, approve=approve)
|
||||
assert req.status == "pending" and skill.current_version_id is None and not audited
|
||||
|
||||
|
||||
def test_an_admin_still_decides_their_own_request(monkeypatch, audited):
|
||||
version = _version()
|
||||
skill = _skill("personal")
|
||||
req = _request(ADMIN)
|
||||
monkeypatch.setattr(skills, "_request_out", lambda _db, _req: {})
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb(request=req, item=skill, version=version)
|
||||
skills.decide_publish(db, ADMIN, req.id, approve=True)
|
||||
assert req.status == "approved" and skill.current_version_id == db.version.id
|
||||
|
||||
|
||||
def test_an_approver_decides_somebody_elses_request(monkeypatch, audited):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
version = _version()
|
||||
skill = _skill("personal")
|
||||
req = _request(OWNER)
|
||||
monkeypatch.setattr(skills, "_request_out", lambda _db, _req: {})
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb([WORKSPACE], request=req, item=skill, version=version)
|
||||
skills.decide_publish(db, OTHER, req.id, approve=True)
|
||||
assert (req.status, req.decided_by, skill.scope) == ("approved", OTHER.id, "firm")
|
||||
|
||||
|
||||
def test_an_imported_slug_takes_the_first_free_number():
|
||||
@@ -212,7 +563,7 @@ def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
||||
# ---- agents ----
|
||||
|
||||
def _sv(skill, current=False):
|
||||
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1)
|
||||
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1, created_by=OWNER.id)
|
||||
if current:
|
||||
skill.current_version_id = version.id
|
||||
return version
|
||||
@@ -354,7 +705,8 @@ def test_get_file_is_404_for_a_version_the_person_cannot_read():
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
stored = SimpleNamespace(media_type="application/yaml", content=b"x")
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_file(_ReadDb(skill, [pending, stored]), OTHER, skill.id, 2, "sprawdzanie.yaml")
|
||||
skills.get_file(_ReadDb(skill, [pending, None, stored]), OTHER, skill.id, 2,
|
||||
"sprawdzanie.yaml")
|
||||
|
||||
|
||||
def test_get_file_is_404_for_a_missing_path():
|
||||
@@ -362,3 +714,38 @@ def test_get_file_is_404_for_a_missing_path():
|
||||
skill = _skill("firm", current=version.id)
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_file(_ReadDb(skill, [version, None]), OTHER, skill.id, 1, "nope.yaml")
|
||||
|
||||
|
||||
def test_an_approver_reads_a_version_in_a_pending_request(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
pending = _full_version(2)
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
stored = SimpleNamespace(media_type="application/yaml", content=b"x")
|
||||
# version, then a pending request for it; the roster of workspace nodes answers `scalars`
|
||||
db = _ReadDb(skill, [pending, uuid.uuid4(), stored], files=[WORKSPACE])
|
||||
assert skills.get_file(db, OTHER, skill.id, 2, "sprawdzanie.yaml") == ("application/yaml", b"x")
|
||||
|
||||
|
||||
def test_an_approver_reads_a_pending_version_of_a_personal_skill(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
pending = _full_version(1)
|
||||
skill = _skill("personal")
|
||||
db = _ReadDb(skill, [pending, uuid.uuid4()], files=[WORKSPACE])
|
||||
assert skills.get_version(db, OTHER, skill.id, 1)["n"] == 1
|
||||
|
||||
|
||||
def test_a_pending_request_grants_nothing_to_somebody_who_may_not_decide(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.editor})
|
||||
skill = _skill("personal")
|
||||
db = _ReadDb(skill, [_full_version(1), uuid.uuid4()], files=[WORKSPACE])
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_version(db, OTHER, skill.id, 1)
|
||||
|
||||
|
||||
def test_a_decided_request_grants_nothing_to_an_approver(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
# the lookup filters on status = pending, so a decided request is the same as none: None
|
||||
db = _ReadDb(skill, [_full_version(2), None], files=[WORKSPACE])
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_version(db, OTHER, skill.id, 2)
|
||||
|
||||
+40
-3
@@ -208,9 +208,10 @@
|
||||
.cats { gap: 6px; }
|
||||
/* The catalogue's two tabs (Moduły · Moje wnioski): an underline, so they never read as one more row of category chips. */
|
||||
.tabs { display: flex; gap: 18px; border-bottom: 1px solid var(--at-border-subtle); margin: -4px 0 16px; }
|
||||
.tabs a { padding: 8px 0; margin-bottom: -1px; border-bottom: 2px solid transparent; color: var(--at-text-secondary); font-size: 14px; }
|
||||
.tabs a:hover { color: var(--at-text); text-decoration: none; }
|
||||
.tabs a.on { color: var(--at-text); border-bottom-color: var(--at-text); font-weight: 550; }
|
||||
.tabs button { border: 0; background: none; font: inherit; cursor: pointer; }
|
||||
.tabs a, .tabs button { padding: 8px 0; margin-bottom: -1px; border-bottom: 2px solid transparent; color: var(--at-text-secondary); font-size: 14px; }
|
||||
.tabs a:hover, .tabs button:hover { color: var(--at-text); text-decoration: none; }
|
||||
.tabs a.on, .tabs button.on { color: var(--at-text); border-bottom-color: var(--at-text); font-weight: 550; }
|
||||
a.chip { cursor: pointer; font-size: 12px; padding: 3px 10px; }
|
||||
a.chip:hover { background: var(--surface-hover); text-decoration: none; }
|
||||
.chip.on, .chip.on:hover { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
@@ -263,6 +264,40 @@ pre.diff {
|
||||
pre.diff.lines { max-width: none; }
|
||||
pre.diff .add { color: var(--ok); background: var(--ok-bg); }
|
||||
pre.diff .del { color: var(--err); background: var(--err-bg); }
|
||||
/* A skill's checking procedure: numbered step cards in one column, in the order the model reads them. */
|
||||
.plan-bar { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; }
|
||||
.plan-steps { list-style: none; margin: 0 0 12px; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.plan-step { display: flex; align-items: flex-start; gap: 12px; padding: 12px; border: 1px solid var(--at-border); border-radius: var(--at-radius-lg); background: var(--surface); }
|
||||
.plan-num {
|
||||
flex: none; width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center;
|
||||
background: var(--surface-2); color: var(--text-secondary); font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.plan-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.plan-name { font-weight: 550; overflow-wrap: anywhere; }
|
||||
.plan-main details .prose { margin-top: 4px; }
|
||||
.plan-chips, .plan-acts { gap: 4px; }
|
||||
.plan-acts { flex: none; }
|
||||
.plan-group + .plan-group { margin-top: 18px; }
|
||||
.plan-group-h { font-size: 13px; font-weight: 600; margin-bottom: 6px; overflow-wrap: anywhere; }
|
||||
.plan-group .tablewrap { margin-bottom: 8px; }
|
||||
.plan-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
|
||||
.plan-ex { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.plan-ex-text { flex: 1; min-width: 0; }
|
||||
.plan-ex textarea, .plan-ex select {
|
||||
width: 100%; box-sizing: border-box; padding: 6px 8px; border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-input); background: var(--surface); color: var(--text); font: inherit; font-size: 13px;
|
||||
}
|
||||
.plan-ex textarea { resize: vertical; line-height: 1.45; }
|
||||
.plan-count { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
/* A version's trial and standards check (Próba) */
|
||||
.trial-head { margin-bottom: 4px; }
|
||||
.trial-part { display: flex; flex-direction: column; gap: 8px; font-variant-numeric: tabular-nums; }
|
||||
.trial-part + .trial-part { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--at-border-subtle); }
|
||||
.trial-part h4.minor { margin: 0; }
|
||||
.trial-advice { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.trial-advice li { display: flex; flex-direction: column; gap: 2px; }
|
||||
.trial-std { font-weight: 550; overflow-wrap: anywhere; }
|
||||
.trial-line { font-variant-numeric: tabular-nums; }
|
||||
/* The one field that ever holds a secret: a freshly minted app token, shown once and never again.
|
||||
Monospace so it can be proof-read character by character, because where the clipboard API is
|
||||
unavailable — plain HTTP is not a secure context — copying it by hand is the fallback. */
|
||||
@@ -306,6 +341,8 @@ pre.diff .del { color: var(--err); background: var(--err-bg); }
|
||||
.hr-kind { display: none; }
|
||||
|
||||
.unit { padding-left: calc(var(--depth, 0) * 12px); }
|
||||
.plan-step { flex-wrap: wrap; }
|
||||
.plan-acts { width: 100%; justify-content: flex-end; }
|
||||
.unit-main { min-width: 0; flex-basis: 100%; }
|
||||
.unit-acts { margin-left: 26px; }
|
||||
.mhead { gap: 14px; }
|
||||
|
||||
+847
-49
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user