Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion autobot-backend/auth_rbac.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def audit_role_denied(user_data: dict, allowed_roles: List[str], user_role: str,

Grouped per user, role and route template, so a non-admin repeating a request can't flood the log.
An unmatched route groups under one constant: the raw path is caller-chosen and would fill the tracker.
Repeats ride on the next row of the same key; a burst followed by silence shows as its first row (#20787).
"""
user = user_data.get("username", "unknown")
route = getattr(request.scope.get("route"), "path", None) or _UNMATCHED_ROUTE
Expand All @@ -134,7 +135,8 @@ def audit_role_denied(user_data: dict, allowed_roles: List[str], user_role: str,
details={
"roles_required": allowed_roles,
"user_role": user_role,
"endpoint": str(request.url.path),
"endpoint": str(request.url.path), # the first path of the window
"route": route, # what the row groups: every path of this template (#20787)
"repeats_since_last_record": repeats,
},
)
Expand Down
4 changes: 3 additions & 1 deletion autobot-backend/auth_rbac_denial_grouping_16333_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ def test_repeats_on_one_route_write_one_row(layer):
for item in range(50):
_deny("bob", path=f"/admin/items/{item}") # one template, many paths: still one route
assert layer.audit_log.call_count == 1
assert layer.audit_log.call_args.kwargs["details"]["repeats_since_last_record"] == 0
details = layer.audit_log.call_args.kwargs["details"]
assert details["repeats_since_last_record"] == 0
assert details["route"] == "/admin/items/{item_id}" # #20787: the row names what it groups


def test_the_next_row_counts_what_the_window_absorbed(layer):
Expand Down
3 changes: 2 additions & 1 deletion autobot-slm-backend/services/refused_session_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

Maintainer decision: audit these, grouped. One person gets one record per window, and the next record
says how many refusals came since; the grouping is the shared ``RepeatGrouper`` (also the backend's
role denials, #16333). The subject comes from a token whose signature has been checked, so nobody can
role denials, #16333). A burst followed by silence shows as its first record alone
(#20787). The subject comes from a token whose signature has been checked, so nobody can
make up names to grow this; the tracked set is capped anyway. Like the permission gate's denials, a
record that can't be written is logged and counted by the writer and never changes the 403.
"""
Expand Down
14 changes: 9 additions & 5 deletions autobot_shared/repeat_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@
# Author: mrveiss
"""Group repeated audit records: one record per key per window, carrying the repeats it absorbed.

Used where a caller can trigger an audit row on every request, so repeats can't flood the store
while each refusal is still counted: the SLM's refused sessions (#20664) and the backend's
role denials (#16333). Per process, so rows are bounded by workers x keys x windows. The tracked
set is capped; when it is full, the keys dropped to make room lose their unreported counts and may
get an extra record, which is the safe way round.
Used where a caller can trigger an audit row on every request, so repeats can't flood the store:
the SLM's refused sessions (#20664) and the backend's role denials (#16333). Per process, so rows
are bounded by workers x keys x windows.

What is NOT recorded (#20787): repeats are reported only by the key's NEXT record. An expired key
that is still tracked reports them when it recurs. They are lost when the key never recurs (a burst
followed by silence shows as its first row alone; nothing runs on a timer to flush them) or when a
full tracker drops the key to make room, in which case it may also get an extra record, the safe
way round. A caller that needs every repeat counted must not use this.
"""

from __future__ import annotations
Expand Down
22 changes: 22 additions & 0 deletions autobot_shared/repeat_grouping_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,25 @@ def test_a_full_tracker_drops_expired_keys_first_and_still_records_a_new_key():
grouper._recent["old"] = (at - 301, repeats)
assert grouper.repeats_to_record("new") == 0
assert set(grouper._recent) == {"live", "new"}


def test_an_expired_key_that_recurs_reports_its_repeats():
"""#20787: with room in the tracker, an expired key's repeats arrive on its next record."""
grouper = RepeatGrouper(window_s=300)
assert grouper.repeats_to_record("burst") == 0
assert all(grouper.repeats_to_record("burst") is None for _ in range(9))
at, repeats = grouper._recent["burst"]
grouper._recent["burst"] = (at - 301, repeats)
assert grouper.repeats_to_record("other") == 0 # not full: nothing is forgotten
assert grouper.repeats_to_record("burst") == 9


def test_a_full_tracker_drops_an_expired_key_with_its_repeats():
"""#20787: stated behaviour, pinned. The repeats are lost when a full tracker drops the key."""
grouper = RepeatGrouper(window_s=300, max_tracked=1)
assert grouper.repeats_to_record("burst") == 0
assert all(grouper.repeats_to_record("burst") is None for _ in range(9))
at, repeats = grouper._recent["burst"]
grouper._recent["burst"] = (at - 301, repeats)
assert grouper.repeats_to_record("other") == 0 # the full tracker forgets the expired key
assert grouper.repeats_to_record("burst") == 0 # its 9 repeats are gone
199 changes: 187 additions & 12 deletions repo_tests/one_admin_gate_16333_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,23 @@
It reads the syntax tree, so prose naming these shapes is not a hit. Also caught: an aliased
``verify_internal_api_key`` import or a ``getattr`` of it, a raw ``compare_digest`` against the
internal key, ``Role.ADMIN`` / ``Role.ADMIN.value`` comparisons, any letter case of the literals,
``startswith``/``endswith("admin")``, a role-named collection holding an admin role (a second
``ADMIN_ROLES``), and a hand-built admin principal (``{"role": "admin"}``, ``user["role"] = "admin"``,
``role="admin"``).
``startswith``/``endswith("admin")``, ``match role: case "admin":``, a role-named collection
holding an admin role (a second ``ADMIN_ROLES``), and a hand-built admin principal
(``{"role": "admin"}``, ``user["role"] = "admin"``, ``user.role = "admin"``, ``role="admin"``).

It also fails on a new FUNCTION named like an admin check (``require_admin``, ``user_has_admin``,
``enforce_ws_admin``, ``is_*admin*``, ``admin_required``...), even one built on ``is_admin_role``: the
existing ones are recorded by (file, qualified name) with the reason each is not a second gate.

Heuristic limits, not caught: a default such as ``role or "admin"`` (no comparison), a regex such as
``re.match("admin", role)``, a decision whose literals arrive from configuration or another module,
and an admin check whose NAME says nothing of admin (``allowed(user)``) or uses a verb outside
``_ADMIN_VERBS``.

Scope: ``autobot-backend``. ``autobot_shared`` holds the canonical predicate
(``auth.permissions.is_admin_role``) and the key check itself, and the SLM is a separate service
with its own admin-only gate (#20628); neither is a second gate inside this backend. The existing sites
(``auth.permissions.is_admin_role``) and the key check itself. The SLM is a separate service with
its own admin-only gate (#20628), and the owner's ruling (b) on #16333 keeps the SLM's own
service-principal path; neither is a second gate inside this backend. The existing sites
are listed below with counts. The pending list only shrinks: PR B of #16333 moves the
``require_role`` sites, and PR C the local checks. Superadmin-only and company-membership
decisions are different concepts, recorded with their reason.
Expand All @@ -35,6 +45,7 @@
from collections import Counter
from pathlib import Path

import pytest
from repo_tests._paths import repo_root
from repo_tests._reach import declare

Expand Down Expand Up @@ -73,6 +84,101 @@
("autobot-backend/llc/services/work_item_service.py", "set"): 1,
}

_GATE = "the one gate is the HTTP route dependency; this delegates to it, then adds a step"
_PREDICATE = "the one predicate (is_admin_role) over a caller record that is not a bare role"
_WS = "the WebSocket admin gate: a socket has no HTTP dependency, so it decides with is_admin_role"
_OWNERSHIP = "a resource rule: the owner OR the one predicate, not an admin gate"
_PLATFORM_CLAIM = "the platform-admin CLAIM (is_platform_admin), a separate concept from the admin role"
_SUPERADMIN = "superadmin ONLY (root reads), stricter than admin"
_ORG_ROLE = "the one predicate OR an org role (org_admin / owner): the org rule widens the gate"
_COMPANY = "a Company OS membership role: admin of ONE company, not the system admin role (#20778)"
_NOT_AUTH = "not authorization: the security scanner probes a target's /admin paths"

#: Functions NAMED like an admin check (``_ADMIN_DEF``), keyed by (file, qualified name), each with the
#: reason it is not a second gate. A new one fails: call ``check_admin_permission`` / ``is_admin_role``
#: inline, or record it here (#16333).
_RECORDED_DEFS: dict[tuple[str, str], str] = {
("api/feature_flags.py", "require_admin_role"): _GATE,
("api/provider_auth_scope.py", "provider_caller_is_admin"): _GATE,
("api/settings_config.py", "require_settings_admin"): _GATE,
("api/system.py", "admin_check"): _GATE + " (a route handler)",
("auth_rbac.py", "check_admin_mcp_tool_permission"): _GATE,
("api/live_events.py", "_is_admin"): _PREDICATE,
("api/redis_mcp/router.py", "_is_admin"): _PREDICATE,
("api/voice_bundle_user.py", "_is_admin"): _PREDICATE,
("services/workflow_rbac.py", "_is_admin"): _PREDICATE,
("transcriber/deps.py", "caller_is_admin"): _PREDICATE + ": the flag authenticate set with it",
("knowledge/remote_read.py", "remote_read_is_admin"): _PREDICATE + ", via caller_reader",
("api/ws_security.py", "authenticate_ws_admin"): _WS,
("api/ws_security.py", "enforce_ws_admin"): _WS + "; refuses with accept-then-close 4001",
("api/task_workspace_ws.py", "_authenticate_ws_admin"): "a pass-through to ws_security.authenticate_ws_admin",
("api/voice_bundle_user.py", "_check_self_or_admin"): _OWNERSHIP,
("api/user_management/dependencies.py", "require_self_or_admin"): _OWNERSHIP,
("services/workflow_automation/workflow_ownership.py", "is_owner_or_admin"): _OWNERSHIP,
("services/workflow_automation/workflow_ownership.py", "require_owner_or_admin"): _OWNERSHIP,
("api/user_management/dependencies.py", "_is_platform_admin_claim"): _PLATFORM_CLAIM,
("api/user_management/dependencies.py", "require_platform_admin_claim"): _PLATFORM_CLAIM,
("api/user_management/dependencies.py", "require_platform_admin"): _PLATFORM_CLAIM,
("chat_workflow/tiered_context_sources.py", "_is_platform_admin"): _PLATFORM_CLAIM,
("knowledge/root_read.py", "is_superadmin_role"): _SUPERADMIN,
("knowledge/root_read.py", "is_superadmin_user"): _SUPERADMIN,
("api/chat_presets.py", "_is_org_admin"): _ORG_ROLE,
("security/session_ownership.py", "SessionOwnershipValidator._is_org_admin_access"): _ORG_ROLE,
("llc/api/budget.py", "_require_budget_admin"): _COMPANY,
("llc/api/budget.py", "_require_limit_admin"): _COMPANY,
("llc/api/company_ceo.py", "_require_owner_or_admin"): _COMPANY,
("llc/api/replay.py", "_check_admin"): _COMPANY,
("llc/api/secrets.py", "_require_secret_admin"): _COMPANY,
("llc/services/authz.py", "require_company_admin"): _COMPANY,
("llc/services/authz.py", "require_company_admin_unless_platform"): _COMPANY,
("llc/services/company.py", "CompanyService._require_gate_admin"): _COMPANY,
("agents/security_scanner_agent.py", "SecurityScannerAgent._check_admin_path"): _NOT_AUTH,
}
_GATE_DEF = ("auth_middleware.py", "check_admin_permission")
_ADMIN_VERBS = "require|ensure|assert|verify|has|check|authorize|authenticate|enforce"
_ADMIN_DEF = re.compile(
rf"^_?(\w+_)?(({_ADMIN_VERBS})_\w*admin(?![a-z])\w*" # require_admin, user_has_admin, enforce_ws_admin
r"|(get|validate)_admin(_user|_role)?" # get_admin_user; not get_admin_dashboard or validate_admin_path
r"|is_\w*admin(?![a-z])\w*)$" # is_admin, is_superadmin_role
r"|^\w+_is_admin$" # caller_is_admin
r"|^\w*admin_(check|required|only|gate)$", # admin_required, _admin_only, tool_admin_check
re.IGNORECASE,
)

#: Planted names the definition detector must catch, and lookalikes it must leave alone.
_PLANTED_ADMIN_DEFS = (
"require_admin",
"require_org_admin_access",
"is_admin",
"_is_superadmin",
"caller_is_admin",
"check_admin_rights",
"tool_admin_only",
"admin_check",
"ensure_admin",
"assert_admin",
"verify_admin",
"has_admin_access",
"get_admin_user",
"validate_admin",
"admin_required",
"_admin_only",
"user_has_admin",
"authorize_admin",
"enforce_admin",
"authenticate_ws_admin",
)
_LOOKALIKE_DEFS = (
"list_admins",
"admin_panel",
"administrator_count",
"is_administrator",
"get_admin_dashboard",
"_validate_admin_path",
"get_all_sysadmin_templates",
"validate_admin_username",
)

#: Pending migration. **Only shrinks.**
_PENDING = {
# SecurityLayer.authenticate_user derives admin from the username; it waits on #20590/#20749,
Expand Down Expand Up @@ -153,10 +259,11 @@ def _role_set(node: ast.AST) -> bool:


def _role_write(node: ast.AST) -> bool:
"""``user["role"] = "admin"`` or ``role="admin"`` passed as a keyword."""
"""``user["role"] = "admin"``, ``user.role = "admin"``, or ``role="admin"`` passed as a keyword."""
if isinstance(node, ast.Assign) and _names_admin(node.value):
return any(
isinstance(t, ast.Subscript) and isinstance(t.slice, ast.Constant) and t.slice.value == "role"
(isinstance(t, ast.Subscript) and isinstance(t.slice, ast.Constant) and t.slice.value == "role")
or (isinstance(t, ast.Attribute) and t.attr == "role")
for t in node.targets
)
return isinstance(node, ast.keyword) and node.arg == "role" and _names_admin(node.value)
Expand Down Expand Up @@ -194,29 +301,53 @@ def _node_kind(node: ast.AST) -> str | None:
return _call_kind(node)
if isinstance(node, ast.Compare) and any(_names_admin(side) for side in (node.left, *node.comparators)):
return "literal"
if isinstance(node, ast.MatchValue) and _names_admin(node.value):
return "literal" # match role: case "admin":
return None


def admin_defs(source: str) -> Counter:
"""Qualified names of functions in *source* named like an admin check, with how often each is defined."""
found: Counter = Counter()

def visit(node: ast.AST, prefix: str) -> None:
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
qualname = f"{prefix}{child.name}"
if not isinstance(child, ast.ClassDef) and _ADMIN_DEF.match(child.name):
found[qualname] += 1
visit(child, f"{qualname}.")
else:
visit(child, prefix)

visit(ast.parse(source), "")
return found


def admin_decisions(source: str) -> Counter:
"""Local admin decisions in *source*, by kind."""
return Counter(kind for node in ast.walk(ast.parse(source)) if (kind := _node_kind(node)))


def _population() -> dict[tuple[str, str], int]:
def _population() -> tuple[dict[tuple[str, str], int], Counter]:
examined = REACH.examined(_ROOT)
found: dict[tuple[str, str], int] = {}
defs: Counter = Counter() # (file, qualname) -> definitions
for rel in examined:
try:
counts = admin_decisions((_ROOT / rel).read_text(encoding="utf-8"))
source = (_ROOT / rel).read_text(encoding="utf-8")
counts, names = admin_decisions(source), admin_defs(source)
except SyntaxError:
continue
found.update({(rel, kind): n for kind, n in counts.items()})
path = rel.removeprefix("autobot-backend/")
defs.update({(path, qualname): n for qualname, n in names.items()})
REACH.completed(len(examined), _ROOT)
return found
return found, defs


def test_no_new_local_admin_decision():
population = _population()
population, _ = _population()
assert ("autobot-backend/auth_service_opt_in.py", "key") in population, "instrument check: the canonical site"
allowed = {**_RECORDED, **_PENDING}
new = {site: n for site, n in population.items() if site not in _CANONICAL and n > allowed.get(site, 0)}
Expand All @@ -227,11 +358,49 @@ def test_no_new_local_admin_decision():


def test_the_pending_list_only_shrinks():
population = _population()
population, _ = _population()
stale = {site: (n, population.get(site, 0)) for site, n in _PENDING.items() if population.get(site, 0) < n}
assert not stale, f"migrated sites still listed (listed, found): {stale}. Lower or delete their entries."


def test_no_new_function_named_like_an_admin_check():
"""#16333 AC: a new local ``def require_admin`` (or ``is_admin``, ``check_*admin*``) fails, even one
built on ``is_admin_role``. The one gate is ``auth_middleware.check_admin_permission``."""
_, defs = _population()
assert defs.get(_GATE_DEF) == 1, "instrument check: the one gate is named like one, and defined once"
new = sorted(f"{p}:{name}" for (p, name) in defs if (p, name) not in _RECORDED_DEFS and (p, name) != _GATE_DEF)
twice = sorted(f"{p}:{name} x{n}" for (p, name), n in defs.items() if n > 1)
assert not new, (
f"new functions named like an admin check: {new}. Use Depends(check_admin_permission) or "
"is_admin_role(...) inline, or record the function in _RECORDED_DEFS with its reason (#16333)."
)
assert not twice, f"a recorded name defined more than once in its file: {twice}; record each by its own name"


def test_recorded_admin_functions_still_exist_and_say_why():
_, defs = _population()
stale = sorted(f"{path}:{name}" for path, name in _RECORDED_DEFS if (path, name) not in defs)
assert not stale, f"recorded functions that no longer exist: {stale}. Delete their entries."
assert all(reason.strip() for reason in _RECORDED_DEFS.values()), "every recorded function states its reason"


@pytest.mark.parametrize("name", _PLANTED_ADMIN_DEFS)
def test_the_def_detector_catches(name):
assert admin_defs(f"def {name}(user): return is_admin_role(user.role)") == Counter({name: 1})


@pytest.mark.parametrize("name", _LOOKALIKE_DEFS)
def test_the_def_detector_leaves_alone(name):
assert admin_defs(f"def {name}(): ...") == Counter()


def test_the_def_detector_keys_by_qualified_name_and_counts_redefinitions():
source = (
"class Gate:\n def require_admin(self): ...\ndef is_admin(u): ...\ndef is_admin(u): ...\nis_admin = True"
)
assert admin_defs(source) == Counter({"Gate.require_admin": 1, "is_admin": 2})


def test_the_detector_reads_code_not_prose():
assert admin_decisions('require_role("admin", "superadmin")') == Counter({"require_role": 1})
assert admin_decisions('if role in ("admin", "superadmin"): pass') == Counter({"literal": 1})
Expand All @@ -256,6 +425,10 @@ def test_the_detector_reads_the_spellings_the_security_review_listed():
assert admin_decisions('make_principal(name="svc", role="admin")') == Counter({"grant": 1})
assert admin_decisions('check = getattr(auth, "verify_internal_api_key")') == Counter({"key": 1})
assert admin_decisions("ok = hmac.compare_digest(header, internal_api_key())") == Counter({"key": 1})
# #20787: two more spellings.
assert admin_decisions('match role:\n case "admin":\n pass') == Counter({"literal": 1})
assert admin_decisions('match role:\n case "admin" | "superadmin":\n pass') == Counter({"literal": 2})
assert admin_decisions('user.role = "admin"') == Counter({"grant": 1})


def test_the_extended_detector_leaves_lookalikes_alone():
Expand All @@ -264,3 +437,5 @@ def test_the_extended_detector_leaves_lookalikes_alone():
assert admin_decisions('ok = path.startswith("/api/admin")') == Counter()
assert admin_decisions("ok = hmac.compare_digest(a, b)") == Counter()
assert admin_decisions('user["name"] = "admin"') == Counter()
assert admin_decisions('user.name = "admin"') == Counter()
assert admin_decisions('match role:\n case "user":\n pass') == Counter()