diff --git a/backend/app/api/identity.py b/backend/app/api/identity.py index 01759cd5..845f9b64 100644 --- a/backend/app/api/identity.py +++ b/backend/app/api/identity.py @@ -27,6 +27,9 @@ router = APIRouter(prefix="/api", tags=["identity"]) #: 人和组的名录(GET /api/directory):只读、给搭建者及以上(main.py 挂 require_role("builder")),岗位绑定、应用授权的 #: 选人控件据此给候选、核对填的名字在不在。只有用户名、显示名、是否停用和组名,不含邮箱、角色、登录时间 directory_router = APIRouter(prefix="/api", tags=["identity"]) +#: 使用者选人的候选(GET /api/directory/candidates,05-已知遗留 (b)):任何登录的人都能调(main.py 挂 require_role("user")), +#: 按用途给候选池,只有用户名和显示名 +candidates_router = APIRouter(prefix="/api", tags=["identity"]) def _iso(value: Any) -> str | None: @@ -224,6 +227,56 @@ async def directory(session: AsyncSession = Depends(get_session)) -> dict[str, A "groups": [{"name": g.name, "label": g.label} for g in known.groups.values()]} +@candidates_router.get("/directory/candidates") +async def candidates(purpose: str, app_id: str | None = None, entry: str | None = None, task_id: str | None = None, + field: str | None = None, q: str | None = None, limit: int = 20, + session: AsyncSession = Depends(get_session)) -> dict[str, Any]: + """使用者选人时的候选:{users: [{username, display_name}], groups: [{name, label}], truncated, needs_query?}。 + + 不给是否停用(停用的直接不列)、角色、邮箱、组成员。purpose=form:表单里的选人控件,带 app_id 和 entry(入口表单) + 或 task_id(待办表单)、field(哪个控件),池按字段的 x-principal 算、缺省是能用这个应用的人,要求调用的人能用这个 + 应用(否则 403);应用授权给了所有人时不带前缀 q 不列(needs_query)。purpose=review:个人应用提交审核,启用的搭建者 + 和管理员。q 按用户名或显示名的开头筛,limit 最多 50。开了登录时提交的值按同一个池核对(auth/directory.principal_errors)。""" + from app.api.coded import CodedHTTPException + from app.api.deps import current_principal + from app.apps.access import app_role, at_least + from app.apps.tree import entry_of, resolve_form + from app.auth.directory import PURPOSES, field_pool, principal_fields, review_pool + from app.db.models_apps import App, AppVersion + from app.db.models_process import Task + + if purpose not in PURPOSES: + raise CodedHTTPException(422, f"候选的用途只能是 {' / '.join(PURPOSES)}", "candidates_purpose") + if purpose == "review": + return (await review_pool(session)).pick(q, limit) | {"groups": []} + principal = current_principal() + bindings: dict[str, Any] | None = None + form: Any = None + task = await session.get(Task, task_id) if task_id else None + app = await session.get(App, task.app_id if task is not None else app_id) if (task or app_id) else None + if app is None or (task_id and task is None): + raise CodedHTTPException(404, "应用或待办不存在", "candidates_not_found") + if not at_least(await app_role(session, principal, app), "use"): + raise CodedHTTPException(403, "你没有这个应用的使用权限,看不到它的候选人", "candidates_forbidden") + if task is not None: + form = task.form + if task.app_version is not None: + bindings = await session.scalar(select(AppVersion.bindings).where( + AppVersion.app_id == app.id, AppVersion.version == task.app_version)) + else: + version = (await session.execute(select(AppVersion).where( + AppVersion.app_id == app.id, AppVersion.version == app.published_version))).scalar_one_or_none() \ + if app.published_version else None + spec = version.spec if version is not None else {} + found = entry_of(spec or {}, entry or "") if entry else None + form = resolve_form(spec or {}, found.get("form")) if found else None + bindings = version.bindings if version is not None else None + target = principal_fields(form).get(field or "") + if target is None: + raise CodedHTTPException(404, "表单里没有这个选人控件", "candidates_not_found") + return (await field_pool(session, app, bindings, target)).pick(q, limit) + + # ---------------------------------------------------------------- 审计 diff --git a/backend/app/apps/entries.py b/backend/app/apps/entries.py index 56bd7c69..76b6980a 100644 --- a/backend/app/apps/entries.py +++ b/backend/app/apps/entries.py @@ -113,6 +113,13 @@ async def start_entry(app_id: str, entry_id: str, values: dict[str, Any], princi form = resolve_form(spec, entry.get("form")) or {"type": "object", "properties": {}} if errors := validate_form(form, values if isinstance(values, dict) else None): raise FormRejected(errors) + # 选人控件:开了登录时按候选池核对(auth/directory.py,05-已知遗留 (b))。以前原样传下去,填错的名字会把待办 + # 派给一个不存在的人——没人能处理,也不报错 + from app.auth.directory import principal_errors + + if errors := await principal_errors(session, app, version.bindings, form, values, + getattr(principal, "mode", "off")): + raise FormRejected(errors) # 表单里的文件(docs/design/normal-user-apps.md N9):核对是提交人在这个入口传的、还没用过,先占住;表单值换成 # 登记的那一份引用(连同 sha256 进运行输入、随封存固定)。发起成功绑到这次运行,发起不成放回去 values, claimed = await _claim_files(form, values, principal, app.id, entry_id) diff --git a/backend/app/apps/forms.py b/backend/app/apps/forms.py index fc4f5ff1..d0f63b67 100644 --- a/backend/app/apps/forms.py +++ b/backend/app/apps/forms.py @@ -28,6 +28,8 @@ _FIELD_KEYS = frozenset({ "minLength", "maxLength", "maxItems", "format", "items", "x-widget", # 文件控件的限制:accept(类型或扩展名的列表)、max_mb(docs/design/normal-user-apps.md §3.8) "x-file", + # 选人控件的候选池:{pool: app | group:<组> | slot:<岗位>}(auth/directory.py,05-已知遗留 (b)) + "x-principal", }) #: 文件控件只认这几项写法 _FILE_FIELD_KEYS = frozenset({"type", "title", "description", "readOnly", "x-widget", "x-file"}) @@ -88,6 +90,13 @@ def _field_problems(field: Any) -> list[str]: return out + _file_field_problems(field) if "x-file" in field: out.append("不是文件控件,不能写文件的限制") + if "x-principal" in field: + from app.auth.directory import pool_problem + + if field.get("x-widget") != "principal": + out.append("不是选人控件,不能写候选范围") + elif problem := pool_problem(field["x-principal"]): + out.append(problem) if kind not in FORM_TYPES: out.append(f"的类型只能是 {' / '.join(FORM_TYPES)}") if "format" in field and field["format"] not in FORM_FORMATS: @@ -153,7 +162,7 @@ def _clean_schema(form: dict[str, Any]) -> dict[str, Any]: continue props[name] = {k: v for k, v in field.items() if k in _FIELD_KEYS and k not in ("format", "x-widget", "x-enum-labels", "title", - "description", "readOnly", "default")} + "description", "readOnly", "default", "x-principal")} return {"type": "object", "properties": props, "required": [r for r in form.get("required") or [] if r in props]} diff --git a/backend/app/apps/spec.py b/backend/app/apps/spec.py index a64b7df0..e8f3edfd 100644 --- a/backend/app/apps/spec.py +++ b/backend/app/apps/spec.py @@ -47,9 +47,10 @@ FILE_FIELD_TYPE = "object" FILE_REF_KEYS = ("file_id", "name", "size", "sha256", "type") #: 表单字段能用的 format。不支持 pattern:JS 和 Python 的正则语义不同,会出现前端放行、后端拒收 FORM_FORMATS = ("date", "date-time", "email", "uri") -#: 表单校验错误的 code。file:文件控件的值不对(没上传、不是本人传的、已经用过、类型或大小不符,app/files/store.py) +#: 表单校验错误的 code。file:文件控件的值不对(没上传、不是本人传的、已经用过、类型或大小不符,app/files/store.py); +#: principal:开了登录时选人控件的值不在候选池里(auth/directory.principal_errors) FORM_ERROR_CODES = ("required", "type", "enum", "minimum", "maximum", "min_length", "max_length", "max_items", "format", - "file") + "file", "principal") class _Strict(BaseModel): diff --git a/backend/app/auth/directory.py b/backend/app/auth/directory.py index 6f689ec1..d981f9bc 100644 --- a/backend/app/auth/directory.py +++ b/backend/app/auth/directory.py @@ -1,6 +1,10 @@ """人和组的名录:选人控件的候选(GET /api/directory)、应用检查核对岗位绑定和授权、改授权时核对填的名字,同一处取、 同一个口径(停用的人也在名录里,标 disabled:已经绑着他的岗位、授权要能认出「这个人停用了」,不是「没有这个人」)。 +使用者选人(表单里的选人控件、个人应用提交审核)不拿整份名录,拿按用途算的候选池(candidates,GET +/api/directory/candidates):只有这件事能选的人,只给用户名和显示名,停用的不列;开了登录时提交的值按同一个池核对 +(docs/design/next-round/05-已知遗留.md (b))。名录整份仍只给搭建者。 + 名录里对不上怎么算看登录方式(同前端 PrincipalPicker): - 账号密码登录:人和组都在本系统里建,名录里没有就是填错了(或人被删了),停用的人处理不了待办——都算错; - 单点登录:人和组第一次登录后才进名录,名录里没有的照实提醒、不拒收;停用的人名录里认得出,照样算错; @@ -10,7 +14,7 @@ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass, field -from typing import Literal +from typing import Any, Literal from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession @@ -95,3 +99,175 @@ def mismatch(directory: Directory, mode: str, kind: str, name: str) -> Mismatch return Mismatch(kind, name, problem, False, f"{what}名录里还没有:单点登录的人和组第一次登录后才进名录,名字要和身份提供方里的一致才生效") return Mismatch(kind, name, problem, True, f"{what}名录里没有") + + +# -------------------------------------------------------------------------- +# 候选池:使用者选人时能选谁(05-已知遗留 (b)) +# -------------------------------------------------------------------------- + +#: 候选池的用途:form 表单里的选人控件(入口表单、待办表单);review 个人应用提交审核选审核的人 +PURPOSES = ("form", "review") +#: 一次最多给几位候选 +CANDIDATES_MAX = 50 +#: 表单字段声明候选池(x-principal.pool):app 能用这个应用的人(缺省);group:<组> 这个组的成员;slot:<岗位> 这个岗位 +#: 绑定的人和组(按应用版本的 bindings) +POOL_APP = "app" +POOL_GROUP = "group:" +POOL_SLOT = "slot:" + + +def pool_problem(value: Any) -> str | None: + """x-principal 的写法对不对:只能是 {pool: app | group:<组> | slot:<岗位>}。没问题为 None。""" + if not isinstance(value, dict) or set(value) != {"pool"} or not isinstance(value.get("pool"), str): + return "的候选范围只能写 {\"pool\": \"app\"}、{\"pool\": \"group:组名\"} 或 {\"pool\": \"slot:岗位\"}" + pool = value["pool"].strip() + if pool == POOL_APP: + return None + for prefix in (POOL_GROUP, POOL_SLOT): + if pool.startswith(prefix) and pool[len(prefix):].strip(): + return None + return "的候选范围只能是 app(能用这个应用的人)、group:组名 或 slot:岗位" + + +def pool_of(field: Any) -> str: + """表单字段声明的候选池;没声明、写法不对的按缺省(能用这个应用的人)。""" + setting = field.get("x-principal") if isinstance(field, dict) else None + if isinstance(setting, dict) and pool_problem(setting) is None: + return setting["pool"].strip() + return POOL_APP + + +@dataclass +class Pool: + """一个候选池。open:池就是全部启用的人(应用授权给了所有人)——不带前缀不列,免得等于发通讯录。""" + users: dict[str, DirectoryUser] = field(default_factory=dict) + groups: dict[str, DirectoryGroup] = field(default_factory=dict) + open: bool = False + + def has(self, name: str) -> bool: + """提交的这个名字在不在池里(用户名或组名)。""" + return name in self.users or name in self.groups + + def pick(self, q: str | None, limit: int = CANDIDATES_MAX) -> dict[str, Any]: + """接口给的那一份:{users: [{username, display_name}], groups: [{name, label}], truncated};按前缀筛 + (用户名或显示名,不分大小写)。池是 open 的、又没带前缀:什么都不给,needs_query 为真。""" + prefix = (q or "").strip().lower() + if self.open and not prefix: + return {"users": [], "groups": [], "truncated": False, "needs_query": True} + limit = max(1, min(int(limit or CANDIDATES_MAX), CANDIDATES_MAX)) + + def hit(*names: str) -> bool: + return not prefix or any(n.lower().startswith(prefix) for n in names if n) + + users = [u for u in sorted(self.users.values(), key=lambda u: u.username) if hit(u.username, u.display_name)] + groups = [g for g in sorted(self.groups.values(), key=lambda g: g.name) if hit(g.name, g.label)] + return {"users": [{"username": u.username, "display_name": u.display_name} for u in users[:limit]], + "groups": [{"name": g.name, "label": g.label} for g in groups[:limit]], + "truncated": len(users) > limit or len(groups) > limit} + + +async def _members(session: AsyncSession, group: str) -> dict[str, DirectoryUser]: + from app.db.models import Group, GroupMember, User + + rows = (await session.execute( + select(User).join(GroupMember, GroupMember.user_id == User.id).join(Group, Group.id == GroupMember.group_id) + .where(Group.name == group, User.disabled.is_(False)))).scalars() + return {u.username: DirectoryUser(u.username, u.display_name or u.username, False) for u in rows} + + +async def _people(session: AsyncSession, items: Iterable[tuple[str, str]]) -> Pool: + """一组(种类, 名字)展开成池:人按名录认(停用的、名录里没有的不列),组列出组本身、再展开成员。""" + from app.db.models import Group, User + + pool = Pool() + items = list(items) + names = sorted({n for k, n in items if k == "user" and n}) + if names: + for u in (await session.execute(select(User).where(User.username.in_(names), User.disabled.is_(False))))\ + .scalars(): + pool.users[u.username] = DirectoryUser(u.username, u.display_name or u.username, False) + groups = sorted({n for k, n in items if k == "group" and n}) + if groups: + for g in (await session.execute(select(Group).where(Group.name.in_(groups)))).scalars(): + pool.groups[g.name] = DirectoryGroup(g.name, g.label or g.name) + pool.users.update(await _members(session, g.name)) + return pool + + +async def _everyone(session: AsyncSession) -> Pool: + from app.db.models import Group, User + + pool = Pool(open=True) + for u in (await session.execute(select(User).where(User.disabled.is_(False)))).scalars(): + pool.users[u.username] = DirectoryUser(u.username, u.display_name or u.username, False) + for g in (await session.execute(select(Group))).scalars(): + pool.groups[g.name] = DirectoryGroup(g.name, g.label or g.name) + return pool + + +async def app_pool(session: AsyncSession, app: Any) -> Pool: + """能用这个应用的人:使用及以上的授权(人、组展开成员),加上管理它的人(管理员、建它的人)。授权给了所有人的,池就是 + 全部启用的人(open)。按 apps/access 的口径:搭建者没有授权时只能查看全部实例,不算「能用」的候选。""" + from app.apps.access import RANK, grants_of + from app.db.models import User + + grants = [g for g in await grants_of(session, app.id) if RANK.get(g.role, 0) >= RANK["use"]] + if any(g.principal_kind == "everyone" for g in grants): + return await _everyone(session) + admins = (await session.execute(select(User.username).where(User.role == "admin"))).scalars() + items = [(g.principal_kind, g.principal) for g in grants] + [("user", a) for a in admins] + if getattr(app, "created_by", None): + items.append(("user", app.created_by)) + return await _people(session, items) + + +async def field_pool(session: AsyncSession, app: Any, bindings: dict[str, Any] | None, field: Any) -> Pool: + """表单里一个选人控件的候选池(按字段的 x-principal,缺省能用这个应用的人)。bindings 是这次用到的应用版本的绑定。""" + pool = pool_of(field) + if pool.startswith(POOL_GROUP): + name = pool[len(POOL_GROUP):].strip() + return Pool(users=await _members(session, name)) + if pool.startswith(POOL_SLOT): + bound = ((bindings or {}).get("slots") or {}).get(pool[len(POOL_SLOT):].strip()) + items = [(str(b.get("kind") or "user"), str(b.get("name") or "")) for b in bound or [] if isinstance(b, dict)] + if any(k == "everyone" for k, _ in items): + return await _everyone(session) + return await _people(session, items) + return await app_pool(session, app) + + +async def review_pool(session: AsyncSession) -> Pool: + """个人应用提交审核能交给谁:启用的搭建者和管理员(同 blueprints/personal._review_targets 的规则)。""" + from app.db.models import User + + rows = (await session.execute(select(User).where(User.role.in_(("builder", "admin")), + User.disabled.is_(False)))).scalars() + return Pool(users={u.username: DirectoryUser(u.username, u.display_name or u.username, False) for u in rows}) + + +def principal_fields(form: Any) -> dict[str, dict[str, Any]]: + """表单里的选人控件:{字段名: 字段}。""" + props = form.get("properties") if isinstance(form, dict) else None + return {name: f for name, f in (props or {}).items() if isinstance(f, dict) and f.get("x-widget") == "principal"} + + +#: 选人控件的值不在候选池里时表单错误的 code(apps/spec.FORM_ERROR_CODES 的 principal) +PRINCIPAL_ERROR_CODE = "principal" + + +async def principal_errors(session: AsyncSession, app: Any, bindings: dict[str, Any] | None, form: Any, + values: Any, mode: str) -> list[dict[str, str]]: + """开了登录时按候选池核对表单里选人控件的值:不在池里的按表单错误交回(code=principal),话写成「「x」不在可选的人里」。 + 关登录不核对:没有用户表,签批记的是各自填的署名。没填的不在这里报(必填由表单校验报)。""" + if mode == "off" or not isinstance(values, dict): + return [] + out: list[dict[str, str]] = [] + for name, f in principal_fields(form).items(): + value = values.get(name) + if value in (None, "") or not isinstance(value, str): + continue + pool = await field_pool(session, app, bindings, f) + if not pool.has(value.strip()): + hint = ":单点登录的人要先登录一次才进名录" if mode == "oidc" else ",请从候选中选择" + out.append({"path": name, "code": PRINCIPAL_ERROR_CODE, "message": f"「{value.strip()}」不在可选的人里{hint}"}) + return out diff --git a/backend/app/main.py b/backend/app/main.py index 657c917a..b2647a1b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -238,6 +238,7 @@ for router, guard in ( (identity_api.router, _ADMIN), # 选人用的名录(用户名、显示名、是否停用、组名):岗位绑定、应用授权由搭建者做,只读 (identity_api.directory_router, _BUILDER), + (identity_api.candidates_router, _USER), # 能力登记、端点:搭建者只读,改动在接口里要管理员 (capabilities_api.router, _BUILDER), # 普通用户建应用:个人应用的接口共用 /api/apps 前缀,要在 apps_api 之前登记;蓝图助手共用 /api/copilot 前缀, diff --git a/backend/app/process/tasks.py b/backend/app/process/tasks.py index 6ec167af..818b4f76 100644 --- a/backend/app/process/tasks.py +++ b/backend/app/process/tasks.py @@ -406,6 +406,22 @@ def _check_hash(card: dict[str, Any], given: Any, *, approving: bool) -> None: status_code=422, code="payload_hash_mismatch") +async def _check_principals(session: AsyncSession, task: Task, principal: Any, values: dict[str, Any]) -> None: + """待办表单里的选人控件:开了登录时按候选池核对(同入口表单,auth/directory.principal_errors)。不属于应用的待办 + (试运行、画布)没有池,不核对。""" + from app.auth.directory import principal_errors + + if not task.app_id or getattr(principal, "mode", "off") == "off": + return + app = await session.get(App, task.app_id) + if app is None: + return + bindings = await session.scalar(select(AppVersion.bindings).where( + AppVersion.app_id == task.app_id, AppVersion.version == task.app_version)) if task.app_version else None + if errors := await principal_errors(session, app, bindings, task.form, values, principal.mode): + raise FormInvalid(errors) + + def _validated(form: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]: from app.apps.forms import validate_form @@ -491,6 +507,8 @@ async def respond(task_id: str, principal: Any, *, decision: Any, values: dict[s rows = (await _assignments(session, [task.id])).get(task.id, []) mine = _pick(task, rows, principal) response, verdict = _engine_response(task, approval, decision, values, note, payload_hash) + if task.form and verdict in ("approve", "submit") and values: + await _check_principals(session, task, principal, values) response = await _bind_files(session, task, principal, response) now = utcnow() marked = await session.execute( diff --git a/backend/tests/test_directory_candidates.py b/backend/tests/test_directory_candidates.py new file mode 100644 index 00000000..c8fe3a36 --- /dev/null +++ b/backend/tests/test_directory_candidates.py @@ -0,0 +1,266 @@ +"""使用者选人:按用途给的候选池 + 开登录时服务端核对(docs/design/next-round/05-已知遗留.md (b))。 + +以前使用者在入口表单、待办表单的选人控件里没有候选(名录只给搭建者),服务端也不核对:填错的名字会把待办派给一个不存在 +的人,没人能处理,也不报错。现在: +- GET /api/directory/candidates 按用途给候选池,只有用户名和显示名,停用的不列;form 用途缺省是能用这个应用的人(使用 + 及以上的授权展开组成员,加上管理员和建应用的人),字段可以用 x-principal 声明别的池;应用授权给了所有人时不带前缀不列; + 调用的人不能用这个应用时 403;review 用途是启用的搭建者和管理员; +- 开了登录时,入口表单和待办表单的选人控件按同一个池核对,不在池里 422(errors 的 code=principal);关登录照旧手填; +- /api/directory 仍然只给搭建者。 + +名字都是虚构的。 +""" +from __future__ import annotations + +import asyncio +import uuid + +import pytest +from sqlalchemy import delete, select + +from app.apps.forms import validate_form_schema +from app.core.artifact_store import graph_hash +from app.db.base import SessionLocal, utcnow +from app.db.models import App, AppGrant, Group, GroupMember, Run, Task, User, Workflow, WorkflowVersion +from app.engine.runner import run_manager +from tests.fakes import auth_env + + +@pytest.fixture(autouse=True) +async def engine_up(): + await run_manager.setup() + yield + await run_manager.shutdown() + + +def node(nid, ntype, label=None, **config): + return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}} + + +def chain(*nodes): + return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]} + + +PICK = {"type": "string", "title": "审批人", "x-widget": "principal"} + +GRAPH = chain( + node("start", "input", "开始", fields=[{"name": "approver"}, {"name": "reviewer"}]), + node("review", "human", "复核", mode="input", title="请指定复核人", + form={"type": "object", "properties": {"reviewer": {**PICK, "title": "复核人"}}}), + node("out", "output", "成果", fields=[{"name": "r", "value": "{{ input.approver }}"}])) + + +async def _workflow() -> tuple[str, str]: + async with SessionLocal() as session: + wf = Workflow(name=f"选人-{uuid.uuid4().hex[:6]}", graph=GRAPH, status="published", published_version=1, + version=1) + session.add(wf) + await session.flush() + session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=GRAPH, graph_hash=graph_hash(GRAPH), + level="published", published_at=utcnow())) + await session.commit() + return wf.id, graph_hash(GRAPH) + + +def _spec(wf: str, hash_: str, approver: dict | None = None) -> dict: + return { + "format": "agentlab.app/1", "name": "选人", + "pins": [{"alias": "main", "workflow_id": wf, "version": 1, "graph_hash": hash_, "use": "entry"}], + "entries": [{"id": "apply", "label": "发起", "pin": "main", "form": {"$ref": "#/forms/apply"}, + "map": {"approver": "form.approver"}}], + "forms": {"apply": {"type": "object", "properties": {"approver": approver or PICK}}}, + "pages": [{"id": "home", "title": "首页", "body": [ + {"id": "new", "type": "entry_button", "props": {"entry": "apply"}}]}], + } + + +async def _new_app(root, spec: dict) -> str: + """root 建一个应用并发布,授权使用给 uma、停用的 dan 和组「财务」。""" + res = await root.post("/api/apps", json={"name": f"选人-{uuid.uuid4().hex[:4]}", "spec": spec}) + assert res.status_code == 201, res.text + app_id = res.json()["id"] + published = (await root.post(f"/api/apps/{app_id}/publish", json={})).json() + assert published["ok"], published + async with SessionLocal() as session: + session.add_all([AppGrant(app_id=app_id, principal_kind="user", principal="uma", role="use"), + AppGrant(app_id=app_id, principal_kind="user", principal="dan", role="use"), + AppGrant(app_id=app_id, principal_kind="group", principal="财务", role="use")]) + await session.commit() + return app_id + + +@pytest.fixture +async def world(): + """开账号密码登录:管理员 root(建应用)、搭建者 bob、使用者 uma(授权使用)、ulf(没授权)、停用的 dan(授权使用); + 组「财务」(fay、fin),整组授权使用。""" + await auth_env.reset() + root = await auth_env.turn_on_local("root") + try: + await auth_env.make_user("bob", "builder") + await auth_env.make_user("uma", "user") + await auth_env.make_user("ulf", "user") + await auth_env.make_user("dan", "user", disabled=True) + fay = await auth_env.make_user("fay", "user") + fin = await auth_env.make_user("fin", "user") + async with SessionLocal() as session: + for username, shown in (("uma", "乌玛"), ("fay", "费伊"), ("bob", "鲍勃")): + user = (await session.execute(select(User).where(User.username == username))).scalar_one() + user.display_name = shown + group = Group(name="财务", label="财务组", source="local") + session.add(group) + await session.flush() + session.add_all([GroupMember(group_id=group.id, user_id=fay.id), GroupMember(group_id=group.id, user_id=fin.id)]) + await session.commit() + wf, hash_ = await _workflow() + app_id = await _new_app(root, _spec(wf, hash_)) + yield {"root": root, "app_id": app_id, "wf": wf, "hash": hash_} + finally: + await root.aclose() + async with SessionLocal() as session: + for model in (AppGrant, App): + await session.execute(delete(model)) + await session.commit() + await auth_env.reset() + + +def _params(app_id: str, **more) -> dict: + return {"purpose": "form", "app_id": app_id, "entry": "apply", "field": "approver", **more} + + +async def test_users_get_the_people_who_can_use_the_app_and_only_their_names(world): + uma = await auth_env.login("uma") + r = await uma.get("/api/directory/candidates", params=_params(world["app_id"])) + assert r.status_code == 200, r.text + body = r.json() + assert [u["username"] for u in body["users"]] == ["fay", "fin", "root", "uma"] + assert all(set(u) == {"username", "display_name"} for u in body["users"]), "不给停用、角色、邮箱" + assert {u["username"]: u["display_name"] for u in body["users"]}["uma"] == "乌玛" + assert body["groups"] == [{"name": "财务", "label": "财务组"}] and body["truncated"] is False + # 前缀按用户名或显示名筛 + assert [u["username"] for u in (await uma.get("/api/directory/candidates", + params=_params(world["app_id"], q="费"))).json()["users"]] == ["fay"] + # 名录整份仍然只给搭建者 + assert (await uma.get("/api/directory")).status_code == 403 + # 不能用这个应用的人拿不到它的候选 + ulf = await auth_env.login("ulf") + assert (await ulf.get("/api/directory/candidates", params=_params(world["app_id"]))).status_code == 403 + for c in (uma, ulf): + await c.aclose() + + +async def test_an_app_granted_to_everyone_needs_a_prefix(world): + async with SessionLocal() as session: + session.add(AppGrant(app_id=world["app_id"], principal_kind="everyone", principal="", role="use")) + await session.commit() + ulf = await auth_env.login("ulf") + body = (await ulf.get("/api/directory/candidates", params=_params(world["app_id"]))).json() + assert body["users"] == [] and body["needs_query"] is True + found = (await ulf.get("/api/directory/candidates", params=_params(world["app_id"], q="u"))).json() + assert [u["username"] for u in found["users"]] == ["ulf", "uma"], "停用的 dan 不列" + capped = (await ulf.get("/api/directory/candidates", params=_params(world["app_id"], q="f", limit=1))).json() + assert len(capped["users"]) == 1 and capped["truncated"] is True + await ulf.aclose() + + +async def test_review_candidates_are_builders_and_admins(world): + uma = await auth_env.login("uma") + body = (await uma.get("/api/directory/candidates", params={"purpose": "review"})).json() + assert [u["username"] for u in body["users"]] == ["bob", "root"] and body["groups"] == [] + assert (await uma.get("/api/directory/candidates", params={"purpose": "nope"})).status_code == 422 + await uma.aclose() + + +async def test_starting_with_a_name_outside_the_pool_is_refused(world): + uma = await auth_env.login("uma") + url = f"/api/apps/{world['app_id']}/entries/apply" + bad = await uma.post(url, json={"values": {"approver": "wangwu"}}) + assert bad.status_code == 422, bad.text + [error] = bad.json()["errors"] + assert (error["path"], error["code"]) == ("approver", "principal") + assert error["message"].startswith("「wangwu」不在可选的人里") + disabled = await uma.post(url, json={"values": {"approver": "dan"}}) + assert disabled.status_code == 422 and disabled.json()["errors"][0]["code"] == "principal" + for ok in ("fay", "财务"): + good = await uma.post(url, json={"values": {"approver": ok}}) + assert good.status_code == 201, good.text + await uma.aclose() + + +async def test_a_task_form_is_checked_against_the_same_pool(world): + uma = await auth_env.login("uma") + started = await uma.post(f"/api/apps/{world['app_id']}/entries/apply", json={"values": {"approver": "fay"}}) + assert started.status_code == 201, started.text + run_id = started.json()["run_id"] + task = None + for _ in range(200): + async with SessionLocal() as session: + task = (await session.execute(select(Task).where(Task.run_id == run_id, Task.status == "pending")))\ + .scalars().first() + if task is not None: + break + await asyncio.sleep(0.05) + assert task is not None + cands = await uma.get("/api/directory/candidates", params={"purpose": "form", "task_id": task.id, + "field": "reviewer"}) + assert cands.status_code == 200 and "fin" in [u["username"] for u in cands.json()["users"]] + root = world["root"] + bad = await root.post(f"/api/tasks/{task.id}/respond", json={"decision": "submit", "values": {"reviewer": "wangwu"}}) + assert bad.status_code == 422, bad.text + assert bad.json()["errors"][0]["code"] == "principal" + good = await root.post(f"/api/tasks/{task.id}/respond", json={"decision": "submit", "values": {"reviewer": "fin"}}) + assert good.status_code == 200, good.text + await uma.aclose() + + +async def test_a_declared_pool_narrows_the_candidates(world): + """x-principal 声明了 group:财务:候选只有组里的人,提交组外的人也拒。""" + app_id = await _new_app(world["root"], _spec(world["wf"], world["hash"], + {**PICK, "x-principal": {"pool": "group:财务"}})) + uma = await auth_env.login("uma") + body = (await uma.get("/api/directory/candidates", params=_params(app_id))).json() + assert [u["username"] for u in body["users"]] == ["fay", "fin"] and body["groups"] == [] + refused = await uma.post(f"/api/apps/{app_id}/entries/apply", json={"values": {"approver": "uma"}}) + assert refused.status_code == 422 and refused.json()["errors"][0]["code"] == "principal" + await uma.aclose() + + +async def test_login_off_takes_any_name(): + await auth_env.reset() + wf, hash_ = await _workflow() + from httpx import ASGITransport, AsyncClient + + from app.main import app as asgi + + async with AsyncClient(transport=ASGITransport(app=asgi), base_url="http://test") as c: + res = await c.post("/api/apps", json={"name": f"关登录-{uuid.uuid4().hex[:4]}", "spec": _spec(wf, hash_)}) + app_id = res.json()["id"] + assert (await c.post(f"/api/apps/{app_id}/publish", json={})).json()["ok"] + started = await c.post(f"/api/apps/{app_id}/entries/apply", json={"values": {"approver": "随手填的名字"}}) + assert started.status_code == 201, started.text + async with SessionLocal() as session: + await session.execute(delete(Run).where(Run.id == started.json()["run_id"])) + await session.execute(delete(App).where(App.id == app_id)) + await session.commit() + + +def test_x_principal_is_checked_in_the_form_schema(): + ok = {"type": "object", "properties": {"a": {**PICK, "x-principal": {"pool": "slot:finance"}}}} + assert validate_form_schema(ok) == [] + bad = {"type": "object", "properties": { + "a": {**PICK, "x-principal": {"pool": "everyone"}}, + "b": {"type": "string", "x-principal": {"pool": "app"}}, + "c": {**PICK, "x-principal": "app"}}} + problems = validate_form_schema(bad) + assert len(problems) == 3, problems + assert any("「b」不是选人控件" in p for p in problems) + + +async def test_users_table_is_untouched_by_candidates(world): + """候选接口只读:不建用户、不改名录。""" + async with SessionLocal() as session: + before = len((await session.execute(select(User.id))).all()) + uma = await auth_env.login("uma") + await uma.get("/api/directory/candidates", params=_params(world["app_id"], q="zz")) + await uma.aclose() + async with SessionLocal() as session: + assert len((await session.execute(select(User.id))).all()) == before