合入 W3-d 邮件、待办汇总、分享链接:邮件渠道(SMTP 可选、口令加密、退信不追踪);每天的待办汇总与访问密钥到期提醒;分享链接(只存哈希、必设到期、只显示定时出数的视图、/s 页不进外壳、下载报告);「最近一次封存」按来源白名单认;使用者拿不到邮件渠道的收件地址;同站门户嵌整站的配置说明

This commit is contained in:
ThearchyHelios
2026-10-16 18:48:07 +08:00
40 changed files with 4168 additions and 171 deletions
+285
View File
@@ -0,0 +1,285 @@
"""每天的待办汇总、访问密钥快到期(notify/digest.py + notify/service,docs/design/next-round/04-对外集成与触达.md B3)。
守的是:
- 待办汇总到设置的时间(notify.digest_at,按服务端时区)才发,只发给订阅了 task.digest 的个人渠道;内容是条数、最早时限、
最多 5 条节点在图上的名字(不是按运行数据渲染出来的待办标题)、去待办箱的链接,不放数;
- 同一天只发一次,重启(进程里记的清掉)也不重发:靠 settings 表里按日期认领的一行;第二天照常发;
- 没有待办的人不发;
- 访问密钥到期前 7 天、1 天各推一次,不多推;个人密钥推本人的个人渠道,服务账号的推全局渠道;每次推都记审计;
- 轮换下来的旧密钥、撤销了的、建的时候就已经在这一档里的(自己设了短有效期),不推。
都用 Webhook 渠道和 httpx.MockTransport 接收;人名、应用名是虚构的。
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
import httpx
import pytest
from sqlalchemy import delete, select
from app.core.crypto import encrypt
from app.db.base import SessionLocal, utcnow
from app.db.models import App, AuditEvent, NotifyChannel, NotifyDelivery, Run, Setting, Task, TaskAssignment, User
from app.notify import core, digest, service
from tests.fakes import auth_env
URL = "https://hooks.example.com/agentlab/digest-91c2"
@pytest.fixture
def received(monkeypatch):
got: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
got.append(json.loads(request.content))
return httpx.Response(200, json={"ok": True})
monkeypatch.setattr(core, "_transport", httpx.MockTransport(handler))
monkeypatch.setattr(core, "RETRY_DELAYS", (0, 0, 0))
async def public(url: str) -> None:
return None
monkeypatch.setattr(service, "personal_url_problem", public)
return got
@pytest.fixture(autouse=True)
async def login_on(received):
"""开着账号密码登录(个人渠道挂在认证过的账号上)。依赖 received:收尾时等推送推完,假的接收端还在。"""
await auth_env.reset()
digest.forget()
async with SessionLocal() as session:
# 别的测试可能留下了 notify 一组、渠道和投递记录:整组换成这里要的,渠道和记录先清掉
await session.execute(delete(Setting).where(Setting.key == "notify"))
await session.execute(delete(NotifyDelivery))
await session.execute(delete(NotifyChannel))
session.add(Setting(key="notify", value={"public_base_url": "https://agentlab.example.com",
"digest_at": "09:00"}))
await session.commit()
await auth_env.turn_on_local()
try:
yield
finally:
await _cleanup()
async def _cleanup() -> None:
await service.drain()
async with SessionLocal() as session:
mine = select(Run.id).where(Run.workflow_name == "汇总测试")
tasks = select(Task.id).where(Task.run_id.in_(mine))
await session.execute(delete(TaskAssignment).where(TaskAssignment.task_id.in_(tasks)))
await session.execute(delete(Task).where(Task.run_id.in_(mine)))
for model in (NotifyDelivery, NotifyChannel):
await session.execute(delete(model))
await session.execute(delete(Run).where(Run.workflow_name == "汇总测试"))
await session.execute(delete(App).where(App.name == "报销审批"))
await session.execute(delete(Setting).where(Setting.key.like(digest.STATE_PREFIX + "%")))
await session.execute(delete(Setting).where(Setting.key == "notify"))
await session.commit()
from app.core import public_url
public_url.remember(None)
digest.forget()
await auth_env.reset()
def local(hour: int, minute: int, *, day: int = 16) -> datetime:
"""服务端所在时区的某个时刻(汇总按服务端时区算)→ UTC。"""
return datetime(2026, 10, day, hour, minute).astimezone().astimezone(timezone.utc)
async def personal(user: User, events: list[str]) -> NotifyChannel:
async with SessionLocal() as session:
row = NotifyChannel(name=f"个人-{user.username}", scope="user", owner_id=user.id, format="generic",
url=encrypt(URL), events=events)
session.add(row)
await session.commit()
return row
async def tasks_for(username: str, n: int, *, label: str = "主管审批") -> None:
graph = {"nodes": [{"id": "review", "type": "human", "data": {"label": label}}], "edges": []}
async with SessionLocal() as session:
app = App(name="报销审批", published_version=1)
session.add(app)
run = Run(workflow_name="汇总测试", status="interrupted", graph=graph, input={"amount": 45678})
session.add(run)
await session.flush()
for i in range(n):
task = Task(run_id=run.id, node_id="review", app_id=app.id, kind="approve",
title=f"审批 45678 元的报销 #{i}", due_at=(utcnow() + timedelta(hours=i + 1)).replace(tzinfo=None))
session.add(task)
await session.flush()
session.add(TaskAssignment(task_id=task.id, principal_kind="user", principal=username))
await session.commit()
# --------------------------------------------------------------------------
# 待办汇总
# --------------------------------------------------------------------------
async def test_digest_is_sent_once_a_day_at_the_set_time(received):
ana = await auth_env.make_user("ana", "user")
bo = await auth_env.make_user("bo", "user")
await personal(ana, ["task.digest"])
await personal(bo, ["task.opened"]) # 没订阅汇总
await tasks_for("ana", 7)
await tasks_for("bo", 2)
assert await digest.digest_due(local(8, 59)) == [], "还没到点"
assert await digest.digest_due(local(9, 0)) == [ana.id]
await service.drain()
[body] = received
assert body["event"] == "task.digest" and body["title"] == "你有 7 条待办"
text = body["text"]
assert "条数:7 条" in text and "最早时限" in text
assert text.count("「主管审批」") == 5, "最多列 5 条,用节点在图上的名字"
assert "另有:2 条" in text and "报销审批" in text
assert "45678" not in json.dumps(body, ensure_ascii=False), "不放按运行数据渲染出来的标题、不放数"
assert body["links"] == [{"label": "去待办箱", "url": "https://agentlab.example.com/apps?tab=inbox"}]
assert await digest.digest_due(local(9, 15)) == [], "同一天只发一次"
digest.forget() # 重启:进程里记的没了
assert await digest.digest_due(local(10, 0)) == [], "重启了也不重发:认领在 settings 表里"
await service.drain()
assert len(received) == 1
async with SessionLocal() as session:
rows = (await session.execute(select(NotifyDelivery).where(NotifyDelivery.event == "task.digest"))).scalars()
assert [(r.subject_kind, r.subject_id, r.status) for r in rows] == [("digest", ana.id, "ok")]
assert await digest.digest_due(local(9, 1, day=17)) == [ana.id], "第二天照常"
async def test_digest_follows_the_configured_time_and_skips_people_with_nothing_pending(received):
cy = await auth_env.make_user("cy", "user")
await personal(cy, ["task.digest"])
async with SessionLocal() as session:
row = await session.get(Setting, "notify")
row.value = {**row.value, "digest_at": "17:30"}
await session.commit()
assert await digest.digest_due(local(9, 0)) == []
assert await digest.digest_due(local(17, 30)) == [cy.id]
await service.drain()
assert received == [], "没有待办不发「0 条」"
async def test_nothing_is_sent_when_login_is_off(received):
"""关登录时「派给我的」认不出是谁(人人等同管理员),访问密钥也不生效:汇总、到期提醒都不发,也不认领今天。"""
ana = await auth_env.make_user("ana", "user")
await personal(ana, ["task.digest"])
await tasks_for("ana", 2)
svc = await auth_env.make_service("svc-off")
key, _ = await auth_env.make_key(svc, days=3)
await _age(key, 30)
from app.auth import remember_settings
remember_settings({})
assert await digest.digest_due(local(9, 0)) == []
assert await digest.keys_due(utcnow()) == []
async with SessionLocal() as session:
assert await session.get(Setting, digest.DIGEST_CLAIM + local(9, 0).astimezone().date().isoformat()) is None
async def test_claim_rows_are_not_listed_as_settings(received):
await digest.digest_due(local(9, 0))
async with auth_env.client() as c:
root = await auth_env.login("root")
body = (await root.get("/api/settings")).json()
assert not [k for k in body if k.startswith(digest.STATE_PREFIX)]
# --------------------------------------------------------------------------
# 访问密钥快到期
# --------------------------------------------------------------------------
async def _expiring_audits(key_id: str) -> list[int]:
async with SessionLocal() as session:
rows = (await session.execute(select(AuditEvent).where(AuditEvent.action == "access_key.expiring",
AuditEvent.subject_id == key_id))).scalars()
return sorted(r.data["days"] for r in rows)
async def _age(key, days: float) -> None:
from app.db.models_identity import AccessKey
async with SessionLocal() as session:
row = await session.get(AccessKey, key.id)
row.created_at = utcnow() - timedelta(days=days)
await session.commit()
async def test_personal_key_reminds_its_owner_at_7_and_1_days(received):
await auth_env.personal_keys(True)
dee = await auth_env.make_user("dee", "user")
mine = await personal(dee, ["key.expiring"])
async with SessionLocal() as session:
session.add(NotifyChannel(name="全局", scope="global", format="generic", url=encrypt(URL),
events=["key.expiring"]))
await session.commit()
key, secret = await auth_env.make_key(dee, days=30, name="周报脚本")
await _age(key, 60)
now = utcnow()
assert await digest.keys_due(now) == [], "离到期还有 30 天"
assert await digest.keys_due(now + timedelta(days=23, hours=1)) == [key.id]
await service.drain()
[body] = received
assert body["event"] == "key.expiring" and "周报脚本" in body["title"] and "7 天后" in body["title"]
assert secret not in json.dumps(body) and key.prefix in body["text"]
assert body["links"] == [{"label": "去轮换", "url": "https://agentlab.example.com/settings/keys"}]
async with SessionLocal() as session:
to = (await session.execute(select(NotifyDelivery.channel_id))).scalars().all()
assert to == [mine.id], "个人密钥只推本人,不推全局渠道"
assert await digest.keys_due(now + timedelta(days=24)) == [], "这一档推过了"
digest.forget()
assert await digest.keys_due(now + timedelta(days=25)) == [], "重启后按审计认得出推过了"
assert await digest.keys_due(now + timedelta(days=29, hours=1)) == [key.id], "到期前 1 天再推一次"
assert await digest.keys_due(now + timedelta(days=29, hours=12)) == []
assert await _expiring_audits(key.id) == [1, 7]
await service.drain()
assert len(received) == 2 and "1 天内" in received[1]["title"]
async def test_service_account_keys_remind_global_channels(received):
svc = await auth_env.make_service("svc-portal")
async with SessionLocal() as session:
glob = NotifyChannel(name="运维群", scope="global", format="generic", url=encrypt(URL), events=["key.expiring"])
session.add(glob)
await session.commit()
key, _ = await auth_env.make_key(svc, days=5, name="门户拉数")
await _age(key, 30)
assert await digest.keys_due(utcnow()) == [key.id]
await service.drain()
[body] = received
assert "服务账号 svc-portal" in body["text"]
async with SessionLocal() as session:
assert (await session.execute(select(NotifyDelivery.channel_id))).scalars().all() == [glob.id]
async def test_keys_that_should_not_remind(received):
from app.db.models_identity import AccessKey
svc = await auth_env.make_service("svc-bi")
async with SessionLocal() as session:
session.add(NotifyChannel(name="运维群", scope="global", format="generic", url=encrypt(URL),
events=["key.expiring"]))
await session.commit()
short, _ = await auth_env.make_key(svc, days=3, name="临时") # 建的时候就只有 3 天:不推 7 天那一档
old, _ = await auth_env.make_key(svc, days=0.5, name="轮换下来的")
await _age(old, 90)
new, _ = await auth_env.make_key(svc, days=90, name="轮换上去的")
revoked, _ = await auth_env.make_key(svc, days=2, name="撤销了的")
await _age(revoked, 30)
async with SessionLocal() as session:
(await session.get(AccessKey, new.id)).rotated_from = old.id
(await session.get(AccessKey, revoked.id)).revoked_at = utcnow()
await session.commit()
assert await digest.keys_due(utcnow()) == []
assert await digest.keys_due(utcnow() + timedelta(days=2, hours=1)) == [short.id], "1 天那一档照推"
await service.drain()
assert len(received) == 1
+7 -4
View File
@@ -32,8 +32,10 @@ URL = "https://hooks.example.com/agentlab/notify-events-5d1c"
#: 本轮登记的六个(总方案 X6)
THIS_ROUND = ("source.changed", "ledger.recall", "eval.regressed", "eval.failed", "task.digest", "key.expiring")
#: 其中已经推送的(第 3 波:定时评测的通知只推全局渠道,notify_eval),其余还没有
PUSHED_THIS_ROUND = {"eval.regressed": {"global"}, "eval.failed": {"global"}}
#: 其中已经实现了推送、打开了订阅的(推给哪几条路):定时评测的两个只推全局渠道(第 3 波 W3-c,notify_eval);每天的待办汇总
#: 只推个人渠道;访问密钥快到期,个人密钥推本人、服务账号的推全局渠道(第 3 波 W3-d,notify/digest.py)。其余还没有
PUSHED_THIS_ROUND = {"eval.regressed": {"global"}, "eval.failed": {"global"},
"task.digest": {"user"}, "key.expiring": {"global", "user"}}
@pytest.fixture
@@ -57,8 +59,9 @@ def test_this_rounds_events_are_registered_once_and_not_pushed_yet():
assert name in service.EVENTS, f"{name} 没有登记"
assert service.EVENTS[name].label, name
if name in PUSHED_THIS_ROUND:
continue
assert service.EVENTS[name].scopes == (), f"{name} 还没有推送:不该有人订阅得到"
assert set(service.EVENTS[name].scopes) == PUSHED_THIS_ROUND[name], name
else:
assert service.EVENTS[name].scopes == (), f"{name} 还没有推送:不该有人订阅得到"
assert len({e.label for e in service.EVENTS.values()}) == len(service.EVENTS), "两个事件叫成了同一句"
assert service.EVENT_LABEL == {k: v.label for k, v in service.EVENTS.items()}
+470
View File
@@ -0,0 +1,470 @@
"""邮件:通知渠道的第五种格式(notify/mail.py,docs/design/next-round/04-对外集成与触达.md B2)。
全程用假的 SMTP 工厂(mail._smtp_factory),不连任何邮件服务器。守的是:
- 个人邮件渠道只发到拥有者在名录里的账号邮箱;账号没有邮箱时记一条失败的投递、写明原因;个人渠道不收地址;
- 全局、应用的邮件渠道填固定的收件地址(最多 20 个,格式不对的拒收);邮件服务没启用时不收新的邮件渠道;
- 4xx(临时错误)和连不上按 1/2/4 秒重试,5xx 不重试;报错里绝不出现口令;
- 邮件里只有标题、状态、链接,纯文本 + 转义过的 HTML,带 List-Unsubscribe;投递记录成功写「已交给邮件服务器」(不说已送达);
- 设置的 mail 一组:口令加密存、读的时候只说配没配;启用时要配全;发件人名称不许换行;只有管理员能改;
- 发测试邮件只发到管理员自己的账号邮箱:关登录、账号没有邮箱时 422 说清怎么办;
- 管理员开了「默认发邮件给待办处理人」:第一次派到待办的人自动有一个个人邮件渠道(默认订阅三项),本人删了不再建回来;
开关缺省关时不建。
人名、地址、主机都是虚构的。
"""
from __future__ import annotations
import json
import smtplib
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import delete, select
from app.core.crypto import encrypt
from app.db.base import SessionLocal
from app.db.models import NotifyChannel, NotifyDelivery, Setting, User
from app.notify import mail, service
from app.notify.core import Message
PASSWORD = "Sm7p-Pa55word-Zq"
class FakeSMTP:
"""假的 SMTP 连接:记下登录、发出的信;box.failures 里排着的异常按顺序在 send_message 上抛。"""
def __init__(self, box: SimpleNamespace) -> None:
self.box = box
def starttls(self, context=None) -> None:
self.box.tls += 1
def login(self, username: str, password: str) -> None:
self.box.logins.append((username, password))
if self.box.auth_error:
# 有的服务器会把收到的内容回显在错误里:报错里也不能出现口令
raise smtplib.SMTPAuthenticationError(535, f"5.7.8 bad credentials {password}".encode())
def send_message(self, em, from_addr=None, to_addrs=None):
if self.box.failures:
raise self.box.failures.pop(0)
self.box.sent.append(SimpleNamespace(from_addr=from_addr, to=list(to_addrs or []), em=em))
return {}
def quit(self) -> None:
self.box.quits += 1
def close(self) -> None:
pass
@pytest.fixture
def smtp(monkeypatch):
box = SimpleNamespace(sent=[], logins=[], failures=[], connects=[], refuse=0, tls=0, quits=0, auth_error=False)
def factory(host, port, security, timeout):
box.connects.append((host, port, security, timeout))
if box.refuse:
box.refuse -= 1
raise ConnectionRefusedError("refused")
return FakeSMTP(box)
monkeypatch.setattr(mail, "_smtp_factory", factory)
monkeypatch.setattr(mail, "RETRY_DELAYS", (0, 0, 0))
return box
@pytest.fixture(autouse=True)
async def clean():
"""前后各清一遍:同一个进程里别的测试留下的渠道、投递记录不算进来。"""
await _clean()
yield
await service.drain()
await _clean()
async def _clean() -> None:
async with SessionLocal() as session:
await session.execute(delete(NotifyDelivery))
await session.execute(delete(NotifyChannel))
await session.execute(delete(Setting).where(Setting.key.in_([mail.GROUP, "notify", service.MAIL_AUTO_KEY])))
await session.execute(delete(User).where(User.username.like("mail-%")))
await session.commit()
from app.core import public_url
public_url.remember(None) # 发信时按库里的对外访问地址对齐了缓存:删了那一行,缓存也清掉
async def configure(**over) -> None:
value = mail.stored_value({"enabled": True, "host": "smtp.example.com", "port": 587, "security": "starttls",
"username": "agentlab", "password": PASSWORD, "from_addr": "agentlab@example.com",
"from_name": "AgentLab", **over})
async with SessionLocal() as session:
row = await session.get(Setting, mail.GROUP)
if row is None:
session.add(Setting(key=mail.GROUP, value=value))
else:
row.value = value
notify = await session.get(Setting, "notify")
if notify is None:
session.add(Setting(key="notify", value={"public_base_url": "https://agentlab.example.com"}))
else:
# 别的测试留下的 notify 一组:对外访问地址换成这里要的(退订头按它拼)
notify.value = {**(notify.value or {}), "public_base_url": "https://agentlab.example.com"}
await session.commit()
async def person(name: str, email: str | None) -> User:
async with SessionLocal() as session:
user = User(username=f"mail-{name}", display_name=name, role="user", email=email)
session.add(user)
await session.commit()
await session.refresh(user)
return user
async def channel(scope: str, owner_id: str | None = None, to: str = mail.PERSONAL_PLACEHOLDER,
events: list[str] | None = None) -> NotifyChannel:
async with SessionLocal() as session:
row = NotifyChannel(name=f"邮件-{scope}", scope=scope, owner_id=owner_id, format="email", url=encrypt(to),
events=events or ["task.opened"])
session.add(row)
await session.commit()
await session.refresh(row)
return row
MESSAGE = {"event": "task.opened", "status": "pending", "title": "新的待办:审批 <b>付款</b>",
"lines": [("状态", "待处理"), ("所在", "应用「报销 & 付款」")],
"links": [("去处理", "https://agentlab.example.com/apps/inbox/t1")]}
async def _deliveries() -> list[NotifyDelivery]:
async with SessionLocal() as session:
return list((await session.execute(select(NotifyDelivery))).scalars())
# --------------------------------------------------------------------------
# 发到谁
# --------------------------------------------------------------------------
async def test_personal_mail_goes_to_the_account_email_only(smtp):
await configure()
ana = await person("ana", "ana@example.com")
row = await channel("user", ana.id)
sent = await service._push([row], MESSAGE, subject_kind="task", subject_id="t1", event="task.opened",
run_id=None, task_id="t1")
assert sent == 1
[mail_out] = smtp.sent
assert mail_out.to == ["ana@example.com"] and mail_out.from_addr == "agentlab@example.com"
assert smtp.logins == [("agentlab", PASSWORD)] and smtp.tls == 1
em = mail_out.em
assert em["Subject"] == "【AgentLab】新的待办:审批 <b>付款</b>"
assert em["List-Unsubscribe"] == "<https://agentlab.example.com/settings/notify>"
assert em["Auto-Submitted"] == "auto-generated"
text = em.get_body(("plain",)).get_content()
html = em.get_body(("html",)).get_content()
assert "状态:待处理" in text and "https://agentlab.example.com/apps/inbox/t1" in text
assert "&lt;b&gt;付款&lt;/b&gt;" in html and "<b>付款</b>" not in html, "HTML 里的内容一律转义"
assert "报销 &amp; 付款" in html
[delivery] = await _deliveries()
assert (delivery.status, delivery.error, delivery.http_status) == ("ok", None, None)
async def test_personal_mail_without_account_email_is_a_failed_delivery_with_the_reason(smtp):
await configure()
bo = await person("bo", None)
row = await channel("user", bo.id)
await service._push([row], MESSAGE, subject_kind="task", subject_id="t1", event="task.opened", run_id=None,
task_id="t1")
assert smtp.sent == [] and smtp.connects == [], "没有邮箱就不连服务器"
[delivery] = await _deliveries()
assert delivery.status == "failed" and delivery.error == mail.NO_EMAIL
assert "设置 → 身份" in delivery.error
async def test_global_mail_goes_to_the_fixed_addresses(smtp):
await configure()
row = await channel("global", to="ops@example.com, lead@example.com")
await service._push([row], MESSAGE, subject_kind="task", subject_id="t1", event="task.opened", run_id=None,
task_id="t1")
assert smtp.sent[0].to == ["ops@example.com", "lead@example.com"]
async def test_disabled_mail_service_records_why(smtp):
await configure(enabled=False)
row = await channel("global", to="ops@example.com")
await service._push([row], MESSAGE, subject_kind="task", subject_id="t1", event="task.opened", run_id=None,
task_id="t1")
[delivery] = await _deliveries()
assert delivery.status == "failed" and delivery.error == mail.NOT_ENABLED and smtp.connects == []
# --------------------------------------------------------------------------
# 重试与报错
# --------------------------------------------------------------------------
def _cfg() -> mail.MailConfig:
return mail.config_of(mail.stored_value({"enabled": True, "host": "smtp.example.com", "port": 587,
"security": "starttls", "username": "agentlab", "password": PASSWORD,
"from_addr": "agentlab@example.com"}))
async def test_temporary_errors_and_refused_connections_are_retried(smtp):
smtp.failures = [smtplib.SMTPDataError(451, b"4.3.0 try again later")]
smtp.refuse = 1
out = await mail.send(_cfg(), ["ana@example.com"], Message(title="t"), label="测试")
assert out.ok is True and out.attempts == 3, "连不上一次、451 一次,第三次交给了邮件服务器"
assert len(smtp.sent) == 1
async def test_permanent_errors_are_not_retried(smtp):
smtp.failures = [smtplib.SMTPDataError(550, b"5.7.1 message rejected")]
out = await mail.send(_cfg(), ["ana@example.com"], Message(title="t"), label="测试")
assert out.ok is False and out.attempts == 1 and out.retryable is False
assert "550" in out.error and "smtp.example.com" in out.error
async def test_retries_stop_after_three(smtp):
smtp.refuse = 10
out = await mail.send(_cfg(), ["ana@example.com"], Message(title="t"), label="测试")
assert out.ok is False and out.attempts == 4 and len(smtp.connects) == 4
assert out.error == "无法连接邮件服务器 smtp.example.com:587"
async def test_errors_never_contain_the_password(smtp, caplog):
smtp.auth_error = True
out = await mail.send(_cfg(), ["ana@example.com"], Message(title="t"), label="测试")
assert out.ok is False and out.attempts == 1, "认证失败(5xx)不重试"
assert PASSWORD not in (out.error or "") and "535" in out.error
assert PASSWORD not in caplog.text
smtp.auth_error = False
smtp.failures = [smtplib.SMTPSenderRefused(553, f"sender {PASSWORD} refused".encode(), "agentlab@example.com")]
out = await mail.send(_cfg(), ["ana@example.com"], Message(title="t"), label="测试")
assert PASSWORD not in (out.error or "")
async def test_partially_refused_recipients_are_said_plainly(smtp, monkeypatch):
monkeypatch.setattr(FakeSMTP, "send_message", lambda self, em, from_addr=None, to_addrs=None: {"x@example.com": (550, b"no")})
out = await mail.send(_cfg(), ["ana@example.com", "x@example.com"], Message(title="t"), label="测试")
assert out.ok is True and out.error == "已交给邮件服务器,其中 1 个收件地址被拒收"
def test_line_breaks_in_titles_never_reach_the_headers():
em = mail.build(_cfg(), ["ana@example.com"], Message(title="新的待办:审批\r\nBcc: x@example.com"), unsubscribe=None)
assert em["Subject"] == "【AgentLab】新的待办:审批 Bcc: x@example.com" and em["Bcc"] is None
def test_ssl_security_uses_no_starttls(smtp):
cfg = mail.config_of(mail.stored_value({"enabled": True, "host": "smtp.example.com", "port": 465,
"security": "ssl", "from_addr": "agentlab@example.com"}))
out = mail._send_once(cfg, ["ana@example.com"], mail.build(cfg, ["ana@example.com"], Message(title="t"),
unsubscribe=None))
assert out.ok and smtp.tls == 0 and smtp.logins == [], "没填用户名不登录"
assert smtp.connects[0][:3] == ("smtp.example.com", 465, "ssl") and smtp.connects[0][3] == mail.TIMEOUT_S
# --------------------------------------------------------------------------
# 渠道接口
# --------------------------------------------------------------------------
@pytest.fixture
async def client():
from app.main import app
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
async def test_mail_channels_need_the_mail_service_and_valid_addresses(client, smtp):
body = {"name": "运维邮件", "scope": "global", "format": "email", "url": "ops@example.com", "events": ["task.opened"]}
refused = await client.post("/api/notify/channels", json=body)
assert refused.status_code == 422 and refused.json()["detail"] == mail.NOT_ENABLED
await configure()
too_many = ", ".join(f"p{i}@example.com" for i in range(21))
r = await client.post("/api/notify/channels", json={**body, "url": too_many})
assert r.status_code == 422 and "最多 20 个" in r.json()["detail"]
r = await client.post("/api/notify/channels", json={**body, "url": "ops@example.com\nnot-an-address"})
assert r.status_code == 422 and "not-an-address" in r.json()["detail"]
made = await client.post("/api/notify/channels", json={**body, "url": "ops@example.com;lead@example.com"})
assert made.status_code == 201, made.text
row = made.json()
assert row["format"] == "email" and row["mail_to"] == ["ops@example.com", "lead@example.com"]
assert row["url_host"] == "" and row["signed"] is False
listed = (await client.get("/api/notify/channels")).json()
assert listed["mail"] == {"enabled": True, "account_email": None}, "关登录时没有账号邮箱"
tested = (await client.post(f"/api/notify/channels/{row['id']}/test")).json()
assert tested["ok"] is True and tested["message"].startswith("已交给邮件服务器")
assert "是否送达以邮件服务器为准" in tested["message"]
deliveries = (await client.get(f"/api/notify/deliveries?channel_id={row['id']}")).json()["items"]
assert [(d["event"], d["status"], d["format"]) for d in deliveries] == [("test", "ok", "email")]
# 只改订阅、不传地址:照旧
kept = await client.patch(f"/api/notify/channels/{row['id']}", json={"events": ["task.opened", "action.unknown"]})
assert kept.status_code == 200 and kept.json()["mail_to"] == ["ops@example.com", "lead@example.com"]
# 换成 Webhook 要填 Webhook 地址
back = await client.patch(f"/api/notify/channels/{row['id']}", json={"format": "generic"})
assert back.status_code == 422 and "Webhook 地址" in back.json()["detail"]
async def test_personal_mail_channel_takes_no_address(smtp):
from tests.fakes import auth_env
await configure()
await auth_env.reset()
try:
await auth_env.turn_on_local()
await auth_env.make_user("mail-uma", "user", email="uma@example.com")
uma = await auth_env.login("mail-uma")
r = await uma.post("/api/notify/channels", json={"name": "我的邮件", "scope": "user", "format": "email",
"url": "someone@example.com", "events": ["task.opened"]})
assert r.status_code == 422 and "账号邮箱" in r.json()["detail"], "个人渠道不能填任意地址(不当中继)"
r = await uma.post("/api/notify/channels", json={"name": "我的邮件", "scope": "user", "format": "email",
"events": ["task.opened", "task.digest"]})
assert r.status_code == 201, r.text
assert r.json()["mail_to"] == ["uma@example.com"]
listed = (await uma.get("/api/notify/channels")).json()
assert listed["mail"] == {"enabled": True, "account_email": "uma@example.com"}
tested = (await uma.post(f"/api/notify/channels/{r.json()['id']}/test")).json()
assert tested["ok"] is True and smtp.sent[-1].to == ["uma@example.com"]
finally:
await auth_env.reset()
async def test_users_listing_channels_do_not_get_global_recipients(smtp):
"""使用者列渠道照样看得到全局、应用渠道(应用的通知里要挑一个,只用名字和 id),但邮件渠道的收件地址只给能改它的人
(搭建者以上):只给条数,不给地址。Webhook 只给主机名,邮件地址不能比它多露(复核 L2)。"""
from tests.fakes import auth_env
await configure()
await auth_env.reset()
try:
await auth_env.turn_on_local()
await auth_env.make_user("mail-uma", "user", email="uma@example.com")
await auth_env.make_user("mail-bo", "builder")
everyone = "finance-lead@example.com, ops@example.com"
made = await channel("global", to=everyone)
await channel("app", to="team@example.com")
uma = await auth_env.login("mail-uma")
mine = await uma.post("/api/notify/channels", json={"name": "我的邮件", "scope": "user", "format": "email",
"events": ["task.opened"]})
assert mine.status_code == 201, mine.text
listed = (await uma.get("/api/notify/channels")).json()["items"]
by = {row["scope"]: row for row in listed}
assert set(by) == {"global", "app", "user"}, "全局、应用渠道照样列(应用的通知里要挑)"
assert "finance-lead" not in json.dumps(listed) and "team@" not in json.dumps(listed), "收件地址不给使用者"
assert "mail_to" not in by["global"] and by["global"]["mail_count"] == 2
assert "mail_to" not in by["app"] and by["app"]["mail_count"] == 1
assert by["user"]["mail_to"] == ["uma@example.com"], "自己的个人渠道照常写发到哪"
bo = await auth_env.login("mail-bo")
shown = {row["id"]: row for row in (await bo.get("/api/notify/channels")).json()["items"]}
assert shown[made.id]["mail_to"] == ["finance-lead@example.com", "ops@example.com"], "能改的人看得到,改地址要整份重填"
finally:
await auth_env.reset()
# --------------------------------------------------------------------------
# 设置
# --------------------------------------------------------------------------
async def test_mail_settings_keep_the_password_encrypted_and_hidden(client):
put = await client.put("/api/settings", json={"values": {"mail": {
"enabled": True, "host": "smtp.example.com", "port": 465, "security": "ssl", "username": "agentlab",
"password": PASSWORD, "from_addr": "agentlab@example.com", "from_name": "流程助手"}}})
assert put.status_code == 200, put.text
shown = put.json()["mail"]
assert shown["password"] is None and shown["password_set"] is True and PASSWORD not in json.dumps(put.json())
async with SessionLocal() as session:
stored = (await session.get(Setting, "mail")).value
assert stored["password"] != PASSWORD and PASSWORD not in json.dumps(stored)
assert mail.config_of(stored).password == PASSWORD
# 整组回写(口令是 null、带着 password_set):口令照旧
again = await client.put("/api/settings", json={"values": {"mail": {**shown, "from_name": "AgentLab"}}})
assert again.status_code == 200 and again.json()["mail"]["password_set"] is True
async with SessionLocal() as session:
assert mail.config_of((await session.get(Setting, "mail")).value).password == PASSWORD
# 空串表示去掉
cleared = await client.put("/api/settings", json={"values": {"mail": {"password": ""}}})
assert cleared.json()["mail"]["password_set"] is False
assert cleared.json()["mail"]["host"] == "smtp.example.com", "只给一项的不冲掉别的"
@pytest.mark.parametrize("value, fragment", [
({"enabled": True}, "SMTP 服务器"),
({"enabled": True, "host": "smtp.example.com"}, "发件地址"),
({"host": "smtp://smtp.example.com"}, "主机名"),
({"port": 70000}, "端口"),
({"security": "tls"}, "加密方式"),
({"from_addr": "not-an-address"}, "发件地址"),
({"from_name": "AgentLab\r\nBcc: x@example.com"}, "换行"),
({"relay": True}, "不支持「relay」"),
])
async def test_mail_settings_are_validated(client, value, fragment):
put = await client.put("/api/settings", json={"values": {"mail": value}})
assert put.status_code == 422, put.text
assert fragment in put.json()["detail"]
async def test_mail_settings_are_admin_only_and_test_mail_goes_to_the_admin(smtp):
from tests.fakes import auth_env
await configure()
await auth_env.reset()
try:
async with auth_env.client() as off:
r = await off.post("/api/settings/mail/test")
assert r.status_code == 422 and r.json()["code"] == "mail_test_no_address", "关登录时没有账号邮箱"
root = await auth_env.turn_on_local()
r = await root.post("/api/settings/mail/test")
assert r.status_code == 422 and "没有邮箱地址" in r.json()["detail"]
async with SessionLocal() as session:
admin = (await session.execute(select(User).where(User.username == "root"))).scalar_one()
admin.email = "root@example.com"
await session.commit()
r = await root.post("/api/settings/mail/test")
assert r.status_code == 200 and r.json()["ok"] is True, r.text
assert "已交给邮件服务器" in r.json()["message"] and smtp.sent[-1].to == ["root@example.com"]
await auth_env.make_user("mail-bea", "builder")
bea = await auth_env.login("mail-bea")
assert (await bea.get("/api/settings")).json()["mail"]["password"] is None, "搭建者读得到,看不到口令"
assert (await bea.put("/api/settings", json={"values": {"mail": {"enabled": False}}})).status_code == 403
assert (await bea.post("/api/settings/mail/test")).status_code == 403
finally:
await auth_env.reset()
# --------------------------------------------------------------------------
# 默认发邮件给待办处理人
# --------------------------------------------------------------------------
async def test_assignees_get_a_personal_mail_channel_only_when_the_admin_turns_it_on(smtp):
from tests.fakes import auth_env
await auth_env.reset()
try:
await auth_env.turn_on_local()
cy = await person("cy", "cy@example.com")
await configure()
assert await service.ensure_assignee_mail([cy.username]) == 0, "缺省关:不建"
await configure(default_for_assignees=True)
assert await service.ensure_assignee_mail([cy.username]) == 1
async with SessionLocal() as session:
[row] = (await session.execute(select(NotifyChannel).where(NotifyChannel.owner_id == cy.id))).scalars()
assert (row.scope, row.format, row.enabled) == ("user", "email", True)
assert row.events == ["task.opened", "action.unknown", "review.done"]
await session.delete(row)
await session.commit()
assert await service.ensure_assignee_mail([cy.username]) == 0, "本人删了就是不要:不再建回来"
finally:
await auth_env.reset()
async def test_assignee_mail_is_not_created_when_login_is_off(smtp):
dee = await person("dee", "dee@example.com")
await configure(default_for_assignees=True)
assert await service.ensure_assignee_mail([dee.username]) == 0, "关登录没有认证过的账号,个人渠道无从挂起"
+4 -1
View File
@@ -109,13 +109,16 @@ async def test_env_locks_the_setting(monkeypatch):
async with client() as c:
body = (await c.get("/api/settings")).json()
assert body["public_url"] == {"value": ENV_URL, "env_locked": True}
assert body[NOTIFY_GROUP] == {"public_base_url": None}, "notify 一组照旧是库里存的那一份"
assert body[NOTIFY_GROUP]["public_base_url"] is None, "notify 一组照旧是库里存的那一份"
r = await put_address(c, SET_URL)
assert r.status_code == 409, r.text
assert r.json()["code"] == "public_url_env_locked" and r.json()["field"] == "notify.public_base_url"
assert "AGENTLAB_PUBLIC_URL" in r.json()["detail"]
# 没改这一项(整组原样写回)不算改:不挡同一请求里别的设置
assert (await put_address(c, None)).status_code == 200
# 同一组里别的项(待办汇总的时间)照常能改:环境变量只锁对外访问地址这一项
r = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"digest_at": "08:15"}}})
assert r.status_code == 200 and r.json()[NOTIFY_GROUP]["digest_at"] == "08:15"
# 只读的 public_url 一组写不进库
r = await c.put("/api/settings", json={"values": {"public_url": {"value": SET_URL, "env_locked": False}}})
assert r.status_code == 200
+8 -7
View File
@@ -33,16 +33,17 @@ async def clean():
async def test_daily_limit_is_a_registered_setting_with_default_200():
async with auth_env.client() as c:
body = (await c.get("/api/settings")).json()
assert body[APPS_GROUP] == {"on_demand_daily_limit": 200, "user_personal_apps": False}
assert body[APPS_GROUP] == {"on_demand_daily_limit": 200, "user_personal_apps": False, "share_links": False}
put = await c.put("/api/settings", json={"values": {APPS_GROUP: {"on_demand_daily_limit": 30}}})
assert put.status_code == 200, put.text
assert put.json()[APPS_GROUP] == {"on_demand_daily_limit": 30, "user_personal_apps": False}
assert put.json()[APPS_GROUP] == {"on_demand_daily_limit": 30, "user_personal_apps": False, "share_links": False}
assert (await c.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 30,
"user_personal_apps": False}
"user_personal_apps": False, "share_links": False}
async with SessionLocal() as session:
assert await apps_settings(session) == {"on_demand_daily_limit": 30, "user_personal_apps": False}
assert apps_values({"on_demand_daily_limit": "坏的", "user_personal_apps": "开"}) == {
"on_demand_daily_limit": 200, "user_personal_apps": False}, "存坏了的按默认"
assert await apps_settings(session) == {"on_demand_daily_limit": 30, "user_personal_apps": False,
"share_links": False}
assert apps_values({"on_demand_daily_limit": "坏的", "user_personal_apps": "开", "share_links": 1}) == {
"on_demand_daily_limit": 200, "user_personal_apps": False, "share_links": False}, "存坏了的按默认"
@pytest.mark.parametrize("value, fragment", [
@@ -81,7 +82,7 @@ async def test_auth_settings_are_not_read_or_written_here():
await auth_env.make_user("bob", "builder")
bob = await auth_env.login("bob")
assert (await bob.get("/api/settings")).json()[APPS_GROUP] == {"on_demand_daily_limit": 200,
"user_personal_apps": False}
"user_personal_apps": False, "share_links": False}
assert (await bob.put("/api/settings", json={"values": {APPS_GROUP: {"on_demand_daily_limit": 1}}})
).status_code == 403, "设置页的应用一组只有管理员能改"
assert (await bob.put("/api/settings", json={"values": {APPS_GROUP: {"user_personal_apps": True}}})
+31 -8
View File
@@ -1,4 +1,5 @@
"""通知设置(api/settings.py 的 notify 一组):定时任务的 Webhook 里拼运行链接用的对外访问地址。
"""通知设置(api/settings.py 的 notify 一组):定时任务的 Webhook 里拼运行链接用的对外访问地址,和每天的待办汇总几点发
(digest_at,缺省 09:00,04 细案 B3)。
- 默认没填(null),通知里就不附运行链接
- 只收 http(s) 开头的完整地址;末尾的 / 去掉、首尾空白去掉,空串当没填;带 ? 或 # 的拒收
@@ -31,9 +32,9 @@ def client() -> AsyncClient:
async def test_default_is_no_link():
async with client() as c:
body = (await c.get("/api/settings")).json()
assert body["notify"] == {"public_base_url": None}
assert body["notify"] == {"public_base_url": None, "digest_at": "09:00"}
async with SessionLocal() as session:
assert await notify_settings(session) == {"public_base_url": None}
assert await notify_settings(session) == {"public_base_url": None, "digest_at": "09:00"}
@pytest.mark.parametrize("given, stored", [
@@ -47,10 +48,10 @@ async def test_saved_and_normalized(given, stored):
async with client() as c:
put = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"public_base_url": given}}})
assert put.status_code == 200, put.text
assert put.json()["notify"] == {"public_base_url": stored}
assert (await c.get("/api/settings")).json()["notify"] == {"public_base_url": stored}
assert put.json()["notify"] == {"public_base_url": stored, "digest_at": "09:00"}
assert (await c.get("/api/settings")).json()["notify"] == {"public_base_url": stored, "digest_at": "09:00"}
async with SessionLocal() as session:
assert await notify_settings(session) == {"public_base_url": stored}
assert await notify_settings(session) == {"public_base_url": stored, "digest_at": "09:00"}
@pytest.mark.parametrize("value, fragment", [
@@ -73,5 +74,27 @@ async def test_invalid_values_are_refused_in_chinese(value, fragment):
def test_broken_stored_value_reads_as_unset():
assert notify_values({"public_base_url": "不是地址"}) == {"public_base_url": None}
assert notify_values("坏掉的") == {"public_base_url": None}
assert notify_values({"public_base_url": "不是地址", "digest_at": "25:00"}) == {"public_base_url": None,
"digest_at": "09:00"}
assert notify_values("坏掉的") == {"public_base_url": None, "digest_at": "09:00"}
@pytest.mark.parametrize("given, ok", [("08:30", True), ("23:59", True), ("00:00", True), ("24:00", False),
("9:00", False), ("09:60", False), (900, False), ("", False)])
async def test_digest_time_is_hh_mm(given, ok):
async with client() as c:
put = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"digest_at": given}}})
if ok:
assert put.status_code == 200, put.text
assert put.json()["notify"]["digest_at"] == given
else:
assert put.status_code == 422
assert "待办汇总的发送时间" in put.json()["detail"]
async def test_changing_digest_time_keeps_the_public_address():
"""只给汇总时间的一组:对外访问地址不被冲成没填(设置页的通知分别保存这两项)。"""
async with client() as c:
await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"public_base_url": "https://agentlab.example.com"}}})
put = await c.put("/api/settings", json={"values": {NOTIFY_GROUP: {"digest_at": "17:45"}}})
assert put.json()["notify"] == {"public_base_url": "https://agentlab.example.com", "digest_at": "17:45"}
+416
View File
@@ -0,0 +1,416 @@
"""分享链接(api/shares.py + apps/resolve.py 的 share 旁路,docs/design/next-round/04-对外集成与触达.md C2)。
守的是:
- 管理员开关缺省关,关着建不了、已有的打不开;只有应用的 manage 能建;个人应用、没发布的、这一页没有定时出数的视图都建不了;
- 到期必填,最长 90 天;
- 读的接口不用登录,只认请求头 X-AgentLab-Share:地址里带 key 不认;库里只有 key 的哈希和开头一截;
- 只解析定时出数(最近封存)的视图:按需视图写明原因、从不发起运行(声明了 auto 的也不);流程组件、报告换成写明原因的说明;
- fixed 模式钉在建分享时的那几次运行上(趋势也停在那一期),latest 跟着最新的封存走;
- 下载报告只认这条分享解析出来的运行,内部就是报告导出(遮罩值写「已遮罩」);
- 撤销、到期回 410 并写明;建、撤销写审计,打开只计数;
- 访问密钥一律调不了分享的接口;
- /s 上的安全头:嵌入白名单用 AGENTLAB_EMBED_ORIGINS、Referrer-Policy: no-referrer。
应用、工作流、人名都是虚构的。
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from datetime import timedelta
from pathlib import Path
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import delete, func, select
from app.core.config import BACKEND_DIR
from app.db.base import SessionLocal, utcnow
from app.db.models import AuditEvent, Run, Setting
from app.db.models_apps import ViewShare
from tests.fakes import auth_env
from tests.test_access_key_use import KPI, formal, published, wait, workflow
from tests.test_access_key_use import world # noqa: F401 - 开登录、建管理员、收尾清掉应用
HEADER = "X-AgentLab-Share"
@pytest.fixture(autouse=True)
async def switch(world): # noqa: F811
await set_switch(True)
yield
async with SessionLocal() as s:
await s.execute(delete(ViewShare))
await s.execute(delete(Setting).where(Setting.key == "apps"))
await s.commit()
async def set_switch(on: bool) -> None:
async with SessionLocal() as s:
row = await s.get(Setting, "apps")
if row is None:
s.add(Setting(key="apps", value={"share_links": on}))
else:
row.value = {**row.value, "share_links": on}
await s.commit()
def anonymous(**headers: str) -> AsyncClient:
"""不带会话 cookie、不带 CSRF 头的客户端:拿到链接的人就是这样打开的。"""
from app.main import app
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test", headers=headers)
def board(wf: str, h: str, *, body: list | None = None, views: dict | None = None) -> dict:
return {"format": "agentlab.app/1", "name": "周报看板",
"pins": [{"alias": "main", "workflow_id": wf, "version": 1, "graph_hash": h, "use": "view"}],
"views": views or {"latest": {"source": {"kind": "latest_sealed", "pin": "main", "from": "formal"}}},
"pages": [{"id": "home", "title": "首页", "body": body or [
{"id": "gmv", "type": "metric", "props": {"label": "销售额"},
"bind": {"view": "latest", "metric": "card.gmv"}},
{"id": "trend", "type": "series", "bind": {"view": "latest", "series": "card.gmv"}}]}]}
def soon(days: float = 30) -> str:
return (utcnow() + timedelta(days=days)).isoformat()
async def share(app_id: str, **body) -> dict:
admin = await auth_env.login("root")
r = await admin.post(f"/api/apps/{app_id}/shares", json={"page_id": "home", "expires_at": soon(), **body})
assert r.status_code == 201, r.text
return r.json()
# --------------------------------------------------------------------------
# 建:开关、权限、到期
# --------------------------------------------------------------------------
async def test_switch_and_manage_are_both_required(world): # noqa: F811
wf, h = await workflow(KPI)
await auth_env.make_user("pia", "user")
app_id = await published(world, board(wf, h), [("user", "pia", "observe")])
admin = await auth_env.login("root")
await set_switch(False)
r = await admin.post(f"/api/apps/{app_id}/shares", json={"page_id": "home", "expires_at": soon()})
assert r.status_code == 403 and r.json()["code"] == "share_links_off" and "允许建分享链接" in r.json()["detail"]
listed = (await admin.get(f"/api/apps/{app_id}/shares")).json()
assert listed["enabled"] is False and listed["items"] == [] and listed["max_days"] == 90
await set_switch(True)
pia = await auth_env.login("pia")
r = await pia.post(f"/api/apps/{app_id}/shares", json={"page_id": "home", "expires_at": soon()})
assert r.status_code == 403 and r.json()["code"] == "app_forbidden", "查看全部实例也不够,要管理权限"
made = await share(app_id)
assert made["path"] == f"/s#{made['key']}" and made["state"] == "active" and made["mode"] == "latest"
async with SessionLocal() as s:
row = await s.get(ViewShare, made["id"])
assert row.key_hash != made["key"] and made["key"] not in json.dumps(
{c.name: str(getattr(row, c.name)) for c in ViewShare.__table__.columns}), "库里没有 key 的明文"
assert row.prefix == made["key"][:6] and made["prefix"] == row.prefix
listed = (await admin.get(f"/api/apps/{app_id}/shares")).json()
assert [i["id"] for i in listed["items"]] == [made["id"]] and "key" not in listed["items"][0]
assert listed["items"][0]["page_title"] == "首页"
@pytest.mark.parametrize("expires, fragment", [(None, "必须设到期时间"), (-1, "现在之后"), (91, "最长 90 天")])
async def test_expiry_is_required_and_at_most_90_days(world, expires, fragment): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
admin = await auth_env.login("root")
body = {"page_id": "home", **({"expires_at": soon(expires)} if expires is not None else {})}
r = await admin.post(f"/api/apps/{app_id}/shares", json=body)
assert r.status_code == 422 and r.json()["code"] == "share_expires_invalid" and fragment in r.json()["detail"]
ok = await admin.post(f"/api/apps/{app_id}/shares", json={"page_id": "home", "expires_at": soon(90)})
assert ok.status_code == 201
async def test_pages_without_sealed_views_and_personal_apps_cannot_be_shared(world): # noqa: F811
wf, h = await workflow(KPI)
on_demand = board(wf, h, views={"latest": {"source": {"kind": "on_demand", "pin": "main"}}},
body=[{"id": "gmv", "type": "metric", "bind": {"view": "latest", "metric": "card.gmv"}}])
app_id = await published(world, on_demand, [])
admin = await auth_env.login("root")
r = await admin.post(f"/api/apps/{app_id}/shares", json={"page_id": "home", "expires_at": soon()})
assert r.status_code == 409 and r.json()["code"] == "share_no_sealed_view"
r = await admin.post(f"/api/apps/{app_id}/shares", json={"page_id": "nope", "expires_at": soon()})
assert r.status_code == 404
draft_only = (await admin.post("/api/apps", json={"name": "草稿", "spec": board(wf, h)})).json()["id"]
world["apps"].append(draft_only)
r = await admin.post(f"/api/apps/{draft_only}/shares", json={"page_id": "home", "expires_at": soon()})
assert r.status_code == 409 and r.json()["code"] == "app_unpublished"
from app.db.models import App
async with SessionLocal() as s:
(await s.get(App, draft_only)).scope = "personal"
await s.commit()
r = await admin.post(f"/api/apps/{draft_only}/shares", json={"page_id": "home", "expires_at": soon()})
assert r.json()["code"] in ("personal.not_shareable", "app_not_found"), r.text
# --------------------------------------------------------------------------
# 打开
# --------------------------------------------------------------------------
async def test_the_page_is_public_but_only_trusts_the_header(world): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
run = await formal(wf)
made = await share(app_id)
async with anonymous() as c:
missing = await c.get("/api/shares/page", params={"key": made["key"]})
assert missing.status_code == 400 and missing.json()["code"] == "share_key_missing", "地址里带的 key 不认"
wrong = await c.get("/api/shares/page", headers={HEADER: made["key"][:-2] + "zz"})
assert wrong.status_code == 404 and wrong.json()["code"] == "share_not_found"
r = await c.get("/api/shares/page", headers={HEADER: made["key"]})
assert r.status_code == 200, r.text
body = r.json()
assert body["format"] == "agentlab.share/1"
assert body["share"]["created_by"] == "root" and body["share"]["mode"] == "latest"
view = body["view"]
assert view["format"] == "agentlab.view/1" and view["sources"]["latest"]["run_id"] == run.id
gmv = view["tree"][0]["data"]
assert gmv["state"] == "ok" and "4,321.5" in gmv["text"], "看到的就是使用者看到的那份"
assert view["sources"]["latest"]["stamp"]["sealed"] is True, "印章照常算"
assert body["downloads"] == [{"view": "latest", "run_id": run.id, "reports": [],
"as_of_text": view["sources"]["latest"]["stamp"]["as_of_text"]}]
async def test_only_sealed_views_and_flow_components_become_placeholders(world): # noqa: F811
wf, h = await workflow(KPI)
spec = board(wf, h, views={
"latest": {"source": {"kind": "latest_sealed", "pin": "main", "from": "formal"}},
"ask": {"source": {"kind": "on_demand", "pin": "main", "auto": True}}}, body=[
{"id": "gmv", "type": "metric", "bind": {"view": "latest", "metric": "card.gmv"}},
{"id": "asked", "type": "metric", "bind": {"view": "ask", "metric": "card.gmv"}},
{"id": "todo", "type": "task_list"},
{"id": "mine", "type": "instance_list"}])
app_id = await published(world, spec, [])
await formal(wf)
made = await share(app_id)
async with SessionLocal() as s:
before = await s.scalar(select(func.count(Run.id)))
async with anonymous(**{HEADER: made["key"]}) as c:
view = (await c.get("/api/shares/page")).json()["view"]
async with SessionLocal() as s:
assert await s.scalar(select(func.count(Run.id))) == before, "打开分享页从不发起运行(声明了 auto 的按需视图也不)"
by = {n["id"]: n for n in view["tree"]}
assert by["gmv"]["data"]["state"] == "ok"
assert by["asked"]["data"]["state"] == "empty" and "只显示定时出数的视图" in by["asked"]["data"]["message"]
for cid, kind in (("todo", "task_list"), ("mine", "instance_list")):
assert by[cid]["type"] == "notice" and by[cid]["share_placeholder"] == kind and by[cid]["props"]["text"]
assert "data" not in by[cid], "不取实例、待办"
async def test_fixed_mode_stays_on_the_runs_it_was_created_with(world): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
first = await formal(wf, "W1")
fixed = await share(app_id, mode="fixed")
latest = await share(app_id)
second = await formal(wf, "W2")
async with anonymous(**{HEADER: fixed["key"]}) as c:
pinned = (await c.get("/api/shares/page")).json()
other = await c.get("/api/shares/report.html", params={"run": second.id})
assert other.status_code == 404 and other.json()["code"] == "share_run_not_shared"
async with anonymous(**{HEADER: latest["key"]}) as c:
moving = (await c.get("/api/shares/page")).json()
assert pinned["view"]["sources"]["latest"]["run_id"] == first.id
points = pinned["view"]["tree"][1]["data"]["series"][-1]["points"]
assert [p["run_id"] for p in points] == [first.id], "趋势也停在建分享的那一期"
assert moving["view"]["sources"]["latest"]["run_id"] == second.id
async def test_runs_issued_from_questions_are_never_the_latest(world): # noqa: F811
"""问数据的答案按口径正式出具的运行(ledger_issue)参数是从某人的提问里绑出来的:应用页、趋势、分享链接(latest 和建
fixed 时取的那次)、视图数据接口的「最近一次封存」都不取它,下载报告也不认它(复核 H1)。"""
from app.engine.launch import launch_run
svc = await auth_env.make_service()
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [("user", "svc-portal", "observe")])
regular = await formal(wf, "W1")
async with SessionLocal() as s:
launched = await launch_run(s, workflow_id=wf, run_class="formal", version=1, input_payload={"week": "W9"},
actor="编辑", origin_kind="ledger_issue", origin={"source_run": "提问那次"},
expect_hash=h)
issued = await wait(launched.id)
assert issued.status == "succeeded" and issued.manifest_hash, "出具的运行成功并封存了,是更新的那一次"
admin = await auth_env.login("root")
page = (await admin.get(f"/api/apps/{app_id}/pages/home")).json()
assert page["sources"]["latest"]["run_id"] == regular.id, "看板不换成某人提问的那组参数"
points = page["tree"][1]["data"]["series"][-1]["points"]
assert [p["run_id"] for p in points] == [regular.id], "趋势里也没有它"
_, secret = await auth_env.make_key(svc, scopes=("apps.read",))
data = (await auth_env.keyed(secret).get(f"/api/apps/{app_id}/views/latest/data")).json()
assert data["state"] == "ok" and data["run_id"] == regular.id, "视图数据接口同一个取法"
fixed = await share(app_id, mode="fixed")
latest = await share(app_id)
for made in (fixed, latest):
async with anonymous(**{HEADER: made["key"]}) as c:
body = (await c.get("/api/shares/page")).json()
assert body["view"]["sources"]["latest"]["run_id"] == regular.id, made["mode"]
refused = await c.get("/api/shares/report.html", params={"run": issued.id})
assert refused.status_code == 404 and refused.json()["code"] == "share_run_not_shared", made["mode"]
def test_every_run_origin_is_classified_for_latest_sealed():
"""每种运行来源都要说清算不算「最近一次封存」:以后加了来源、没在 apps/resolve 归类的,这里先失败。"""
from app.apps.resolve import NOT_SEALED_ORIGINS, SEALED_ORIGINS
from app.engine.origin import ORIGIN_KINDS
assert not set(SEALED_ORIGINS) & set(NOT_SEALED_ORIGINS)
assert set(SEALED_ORIGINS) | set(NOT_SEALED_ORIGINS) == set(ORIGIN_KINDS)
assert "ledger_issue" in NOT_SEALED_ORIGINS and "app_backfill" in NOT_SEALED_ORIGINS
async def test_report_download_only_for_the_shares_runs_and_masked(world, monkeypatch, tmp_path): # noqa: F811
import sqlite3
from app.data.engine import engines
from app.engine.launch import launch_run
from tests import test_report_masked_metrics as vipmod
path = tmp_path / "vip.db"
db = sqlite3.connect(path)
db.executescript("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, phone TEXT);")
db.executemany("INSERT INTO customers VALUES (?, ?, ?)", vipmod.CUSTOMERS)
db.commit()
db.close()
source_id = await vipmod.set_source(path, {"mask_columns": ["phone"]})
await engines.invalidate(source_id)
world["sources"].append("vip")
vipmod.script(monkeypatch, vipmod.CLEAN)
wf, h = await workflow(vipmod.graph(on_violation="flag"))
spec = board(wf, h, body=[{"id": "n", "type": "metric", "bind": {"view": "latest", "metric": "card.n_cust"}},
{"id": "doc", "type": "report", "bind": {"view": "latest", "report": "write"}}])
app_id = await published(world, spec, [])
async with SessionLocal() as s:
launched = await launch_run(s, workflow_id=wf, run_class="formal", version=1, input_payload={},
actor="编辑", origin_kind="launcher")
run = await wait(launched.id)
assert run.status == "succeeded", run.error
made = await share(app_id)
kpi_wf, _ = await workflow(KPI)
stranger = await formal(kpi_wf)
async with anonymous(**{HEADER: made["key"]}) as c:
body = (await c.get("/api/shares/page")).json()
by = {n["id"]: n for n in body["view"]["tree"]}
assert by["doc"]["type"] == "notice" and "下载报告" in by["doc"]["props"]["text"], "报告正文不在线打开"
[download] = body["downloads"]
assert download["run_id"] == run.id and download["reports"] == ["write"]
report = await c.get("/api/shares/report.html", params={"run": run.id})
assert report.status_code == 200, report.text
assert "attachment" in report.headers["content-disposition"]
assert vipmod.leaks(report.text) == [], "报告里没有遮罩列的原值"
refused = await c.get("/api/shares/report.html", params={"run": stranger.id})
assert refused.status_code == 404 and refused.json()["code"] == "share_run_not_shared"
no_header = await anonymous().get("/api/shares/report.html", params={"run": run.id})
assert no_header.status_code == 400
async with SessionLocal() as s:
exported = (await s.execute(select(AuditEvent).where(AuditEvent.action == "report.exported",
AuditEvent.subject_id == run.id))).scalars().all()
assert [(e.actor, e.verified) for e in exported] == [(None, False)], "导出记审计,导出人不冒充谁"
async def test_revoked_and_expired_links_say_so_with_410(world): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
await formal(wf)
gone = await share(app_id)
old = await share(app_id)
admin = await auth_env.login("root")
r = await admin.delete(f"/api/apps/{app_id}/shares/{gone['id']}")
assert r.status_code == 200 and r.json()["state"] == "revoked" and r.json()["revoked_by"] == "root"
async with SessionLocal() as s:
(await s.get(ViewShare, old["id"])).expires_at = utcnow() - timedelta(minutes=5)
await s.commit()
async with anonymous() as c:
r = await c.get("/api/shares/page", headers={HEADER: gone["key"]})
assert r.status_code == 410 and r.json()["code"] == "share_revoked" and "链接已撤销" in r.json()["detail"]
r = await c.get("/api/shares/page", headers={HEADER: old["key"]})
assert r.status_code == 410 and r.json()["code"] == "share_expired" and "链接已到期" in r.json()["detail"]
live = await share(app_id)
await set_switch(False)
async with anonymous(**{HEADER: live["key"]}) as c:
r = await c.get("/api/shares/page")
assert r.status_code == 403 and r.json()["code"] == "share_links_off", "管理员关掉开关,已有的一并打不开"
assert (await admin.delete(f"/api/apps/{app_id}/shares/{live['id']}")).status_code == 200, "关着也能撤销"
async def test_create_and_revoke_are_audited_and_opening_only_counts(world): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
await formal(wf)
made = await share(app_id, embed_allowed=True)
async with anonymous(**{HEADER: made["key"]}) as c:
for _ in range(3):
assert (await c.get("/api/shares/page")).status_code == 200
admin = await auth_env.login("root")
await admin.delete(f"/api/apps/{app_id}/shares/{made['id']}")
await admin.delete(f"/api/apps/{app_id}/shares/{made['id']}")
async with SessionLocal() as s:
row = await s.get(ViewShare, made["id"])
actions = (await s.execute(select(AuditEvent.action, AuditEvent.actor).where(
AuditEvent.subject_id == made["id"]).order_by(AuditEvent.at))).all()
assert row.open_count == 3 and row.last_opened_at is not None and row.embed_allowed is True
assert actions == [("app.share_create", "root"), ("app.share_revoke", "root")], "打开不记审计;撤销两次只记一次"
async def test_access_keys_cannot_reach_share_routes(world): # noqa: F811
wf, h = await workflow(KPI)
app_id = await published(world, board(wf, h), [])
made = await share(app_id)
svc = await auth_env.make_service()
_, secret = await auth_env.make_key(svc)
c = auth_env.keyed(secret, **{HEADER: made["key"]})
for method, path in (("GET", "/api/shares/page"), ("GET", f"/api/apps/{app_id}/shares"),
("POST", f"/api/apps/{app_id}/shares")):
r = await c.request(method, path, json={"page_id": "home", "expires_at": soon()} if method == "POST" else None)
assert r.status_code == 403 and r.json()["code"] == "key_route_forbidden", (method, path)
# --------------------------------------------------------------------------
# /s 的安全头
# --------------------------------------------------------------------------
_PROBE = r"""
import asyncio, json, httpx
from app.main import app
async def main():
t = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=t, base_url="http://t") as c:
out = {}
for p in ("/s", "/apps/x", "/api/shares/page"):
r = await c.get(p)
out[p] = {"status": r.status_code, **{k: r.headers.get(k) for k in (
"content-security-policy", "x-frame-options", "referrer-policy")}}
print(json.dumps(out))
asyncio.run(main())
"""
def test_share_page_uses_the_embed_whitelist_and_no_referrer(tmp_path: Path) -> None:
dist = tmp_path / "dist"
(dist / "assets").mkdir(parents=True)
(dist / "index.html").write_text("<!doctype html><html><body><div id=root></div></body></html>")
env = {**os.environ, "AGENTLAB_DATA_DIR": str(tmp_path / "data"), "AGENTLAB_WEB_DIST": str(dist),
"AGENTLAB_SECRET_KEY": "test-only-not-a-real-key", "AGENTLAB_EMBED_ORIGINS": "https://bi.example.org",
"AGENTLAB_FRAME_ANCESTORS": ""}
proc = subprocess.run([sys.executable, "-c", _PROBE], cwd=BACKEND_DIR, env=env, capture_output=True, text=True,
timeout=120)
assert proc.returncode == 0, proc.stderr[-2000:]
out = json.loads(proc.stdout.strip().splitlines()[-1])
assert out["/s"]["status"] == 200, "分享页由页面托管给出(不进外壳由前端定)"
assert out["/s"]["content-security-policy"] == "frame-ancestors 'self' https://bi.example.org"
assert out["/s"]["x-frame-options"] is None and out["/s"]["referrer-policy"] == "no-referrer"
assert out["/apps/x"]["content-security-policy"] == "frame-ancestors 'self'", "别的页面不跟着放开嵌入"
assert out["/apps/x"]["x-frame-options"] == "SAMEORIGIN"
assert out["/api/shares/page"]["status"] == 400, "关登录时也只认请求头"
+1 -1
View File
@@ -4,7 +4,7 @@
- 页面、/api 的响应(连同登录检查自己回的 401)都带 nosniff、Referrer-Policy 和 CSP frame-ancestors;
- frame-ancestors 缺省 'self',只有 'self' 时另加 X-Frame-Options: SAMEORIGIN;配了 AGENTLAB_FRAME_ANCESTORS 白名单时
以 CSP 为准、不发 XFO(XFO 写不了白名单,两个都发的话老浏览器按 XFO 把白名单里的门户也拦了);
- 分享页 /s 用 AGENTLAB_EMBED_ORIGINS、Referrer-Policy: no-referrer(路由第 3 波才加,头的规则先守住);
- 分享页 /s 用 AGENTLAB_EMBED_ORIGINS、Referrer-Policy: no-referrer(真实页面托管下的头另见 test_shares.py);
- 严格的 script-src 只发 Content-Security-Policy-Report-Only,只在页面(index.html)上发,哈希就是构建产物里内联
脚本的 sha256;接口返回的 HTML(导出的报告自带 meta CSP)不带它;
- 接口自己设过的同名头不覆盖、不重复;WebSocket 不经过它;