Files
Atrium/backend/tests/test_skills_console.py
T

239 lines
10 KiB
Python

"""The skills-and-agents screens in the console (Skille i agenci, Administracja → Prośby o publikację).
DB-free.
Source-reading, like `test_providers_console.py`, and honest about what that proves: the screens are
routed, call only routes the backend declares (method included), escape what they render, keep the
publish queue behind the administrator check and never leave this module by a root-absolute
address. That the routes behave is `test_skills_integration.py`'s job.
"""
from __future__ import annotations
import pathlib
import re
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
@pytest.fixture(scope="module")
def console() -> str:
return (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
def _section(console: str, start: str, end: str) -> str:
assert start in console and end in console, (start, end)
return console.split(start, 1)[1].split(end, 1)[0]
@pytest.fixture(scope="module")
def screen(console) -> str:
return (_section(console, "/* ── skills and agents ──", "function openTokenNew(")
+ _section(console, "/* ── administration: publish requests", "/* ── administration: organization"))
@pytest.fixture(scope="module")
def queue(console) -> str:
return _section(console, "/* ── administration: publish requests", "/* ── administration: organization")
def _declared() -> set[tuple[str, str]]:
"""(METHOD, path) for every route in routers/skills.py, path parameters as `{}`."""
src = (ROOT / "backend" / "app" / "routers" / "skills.py").read_text(encoding="utf-8")
prefixes = dict(re.findall(r'^(\w+) = APIRouter[(]prefix="([^"]+)"', src, re.M))
assert set(prefixes) == {"router", "agents", "publish_requests"}
out = set()
for name, method, path in re.findall(r'^@(\w+)[.](get|post)[(]"([^"]*)"', src, re.M):
out.add((method.upper(), re.sub(r"\{[^}]+\}", "{}", prefixes[name] + path)))
return out
def _first_arg(src: str, at: int) -> str:
"""The JS expression starting at `at`, up to the first top-level `,` or the closing `)`."""
depth, i, quote = 0, at, None
while i < len(src):
c = src[i]
if quote:
if c == "\\":
i += 1
elif c == quote:
quote = None
elif quote == "`" and src.startswith("${", i):
end = src.index("}", i) # interpolations here hold no braces
i = end
elif c in "'\"`":
quote = c
elif c in "([{":
depth += 1
elif c in ")]}":
if depth == 0:
break
depth -= 1
elif c == "," and depth == 0:
break
i += 1
return src[at:i]
def _path(expr: str) -> str:
"""A JS path expression as a route template: every interpolation and every `+ <call>` piece
becomes `{}`; a query (`?…`, `+ q`) is dropped."""
expr = re.sub(r"\$\{[^}]*\}", "{}", expr)
parts = [x.strip() for x in re.split(r"\s\+\s", expr)]
out = ""
for part in parts:
if part[:1] in "'`":
out += part.strip("'`")
elif part == "API":
continue
elif re.fullmatch(r"enc[(][^)]*[)]", part):
out += "{}"
else:
break # a query string built at run time
return out.split("?", 1)[0]
def _called(screen: str) -> set[tuple[str, str]]:
calls = {(m.group(1), _path(_first_arg(screen, m.end())))
for m in re.finditer(r"\b(?:api|mutate)[(]'([A-Z]+)', ", screen)}
# Exports are plain links on API, not api() calls.
calls |= {("GET", _path(_first_arg(screen, m.end()))) for m in re.finditer(r"esc[(](?=API \+)", screen)}
# The decision dialog is shared with access requests and takes its queue as an argument, and its
# last segment is `approve ? 'approve' : 'decline'` (pinned by test_the_decision_goes_...).
out = set()
for m, p in calls:
p = p.replace("/admin/{}/", "/admin/publish-requests/")
if p == "/admin/publish-requests/{}/{}":
out |= {(m, "/admin/publish-requests/{}/approve"), (m, "/admin/publish-requests/{}/decline")}
else:
out.add((m, p))
return out
def test_the_screens_are_routed(console):
nav = _section(console, "const NAV = [", "];")
assert "'#/skills'" in nav
assert "else if (seg[0] === 'skills' && seg[1] === 'skill' && seg[2]) await viewSkill(C, seg[2]);" in console
assert "else if (seg[0] === 'skills' && seg[1] === 'agent' && seg[2]) await viewAgent(C, seg[2]);" in console
assert "else if (seg[0] === 'skills') await viewSkills(C, seg[1] === 'firm' ? 'firm' : 'mine');" in console
for fn in ("viewSkills", "viewSkill", "viewAgent", "viewAdminPublishRequests"):
assert f"async function {fn}(" in console
def test_the_publish_queue_is_administrator_only(console):
admin_nav = _section(console, "const ADMIN_NAV = [", "\n];")
assert "'#/admin/publish-requests'" in admin_nav
assert "'#/admin/publish-requests'" not in _section(console, "const NAV = [", "];")
# Reached only through adminRoute, which the router enters only for an administrator.
assert "else if (seg[0] === 'admin' && isAdmin()) await adminRoute(C, seg.slice(1), q);" in console
admin_route = _section(console, "async function adminRoute(", "\n}\n")
assert "if (page === 'publish-requests') return viewAdminPublishRequests(C);" in admin_route
assert console.count("viewAdminPublishRequests(") == 2 # its definition and that one call
def test_it_calls_only_routes_that_exist(screen):
declared = _declared()
called = _called(screen)
assert len(called) >= 15, called
assert called <= declared, called - declared
def test_the_route_reader_sees_every_kind_of_call():
"""Guard the guard: each spelling the screens use turns into the right template."""
sample = """
api('GET', '/skills/' + enc(id));
api('GET', `/skills/${enc(id)}/versions/${v.n}`);
api('POST', '/skills/import' + q + (addVersion ? '&add_version=true' : ''), f);
mutate('POST', `/admin/${queue}/${enc(id)}/${approve ? 'approve' : 'decline'}`, { note: 1 });
href="${esc(API + '/agents/' + enc(a.id) + '/export')}"
"""
assert _called(sample) == {
("GET", "/skills/{}"), ("GET", "/skills/{}/versions/{}"), ("POST", "/skills/import"),
("POST", "/admin/publish-requests/{}/approve"), ("POST", "/admin/publish-requests/{}/decline"),
("GET", "/agents/{}/export"),
}
def test_the_decision_goes_only_to_approve_or_decline(queue, console):
send = _section(console, "function sendDecision(", "\n}\n")
assert "${approve ? 'approve' : 'decline'}" in send
assert {("POST", "/admin/publish-requests/{}/approve"), ("POST", "/admin/publish-requests/{}/decline")} <= _declared()
assert queue.count("'publish-requests')") == 2
def _text_builders(screen: str) -> str:
"""Drop the helpers that build PLAIN TEXT (lines to diff, D3 notes): their output is escaped
where it is rendered (`diffHtml` → esc, `infoNote` → dat), not where it is assembled."""
for name in ("versionText", "agentVersionText", "infoLines"):
screen = re.sub(rf"const {name} = .*?;\n(?=\S|\n)", "", screen, flags=re.S)
return screen
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."""
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))
exprs = _interpolations(code)
assert len(exprs) > 50, len(exprs)
bare = []
for e in exprs:
if _wrapped(e):
continue
# Literals and nested templates are checked on their own; what is left is the top level.
top = re.sub(r"'(?:[^'\\]|\\.)*'|`[^`]*`", "''", e).strip()
# The whole expression, or a branch of a ternary/fallback, read straight off an object.
# A part followed by `?` or `&&` is a condition, not what gets rendered.
bits = re.split(r"(\?|:|\|\||&&)", top) + [""]
for part, op in zip(bits[::2], bits[1::2], strict=False):
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
def _wrapped(e: str) -> bool:
"""The whole expression is one esc()/dat()/enc() call."""
m = re.match(r"(?:esc|dat|enc)[(]", e)
if not m:
return False
depth = 0
for i, c in enumerate(e[m.end() - 1:], m.end() - 1):
depth += {"(": 1, ")": -1}.get(c, 0)
if depth == 0:
return i == len(e) - 1
return False
def _interpolations(code: str) -> list[str]:
"""Every `${...}` expression, nested ones included, by brace depth."""
out, i = [], 0
while (i := code.find("${", i)) != -1:
depth, j = 1, i + 2
while depth and j < len(code):
depth += {"{": 1, "}": -1}.get(code[j], 0)
j += 1
out.append(code[i + 2:j - 1])
i += 2
return out
def test_no_root_absolute_href_or_src(screen):
"""A leading slash would leave /atrium for a sibling's backend (CLAUDE.md, path-mounting)."""
assert not re.search(r"""\b(?:href|src|action)=["'`]?/(?!/)""", screen)
assert "location.href = '/" not in screen and "location.href = `/" not in screen
# Downloads go through the derived API base, never a literal /api/v1.
assert "/api/v1" not in screen
@pytest.mark.parametrize("phrase", [
"Skille i agenci", "Moje", "Firmowe", "Prośby o publikację", "Brak próśb o publikację.",
"Zatwierdź", "Odrzuć", "Pierwsza publikacja w firmie", "plik do pobrania, model go jeszcze nie czyta",
"Zapisane tylko jako informacja:",
])
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}"