Security auditing #1

Merged
zevaryx merged 53 commits from audit into dev 2026-11-17 20:06:45 +00:00
Owner

Lots of small bug fixes, nothing severe

Lots of small bug fixes, nothing severe
A dropped connection, a timeout or a body that is not JSON (an HTML error page from a proxy, a rate limit answer without retry_after) escaped the client as an httpx or ValueError exception and became a 500, sometimes after the sign-in had already exchanged its code. Every request now goes through one place that raises DiscordError(DiscordError.UNREACHABLE) instead, the token exchange and /users/@me check that the answer has the fields that are used, and the Retry-After wait is capped and never NaN.

/users/@me/guilds was read once, so someone in more than 200 servers lost the rest. The user's list is now paged like the bot's own (with a page limit as a safety stop), and both share the code.

The test FakeDiscord can fail the sign-in calls, and a real_discord() helper runs the real client against an httpx MockTransport to page lists and drop connections.
isdigit() accepts characters such as "²" that int() then refuses, and int() reads numbers far beyond what MongoDB can store, so a form field, query string or path like that reached the database and failed with a 500. webui/numbers.py now reads plain ASCII digits within a range (parse_int, parse_snowflake and require_* versions that raise the 422), and every form field that took a number or ID uses it: actions, tools, automation, cases, members, escalation rules, settings and the admin block length (bounded to the bot's own one year). Path IDs are typed SnowflakePath and page numbers PageQuery, so FastAPI refuses out-of-range ones before any query.
Discord takes every permission but View Channel and Read Message History from a timed-out member who is not an administrator, but the website worked rights out from roles alone, so a timed-out moderator could still warn, ban or change settings from here. resolve_access now reads communication_disabled_until and does the same; a timestamp that cannot be read counts as a timeout.

perms.py also gains the role-hierarchy helpers the next fixes use: a member's top role position, and role_problem(), which combines the bot's own rules (no dangerous permissions, nothing managed or above the bot) with Discord's rule that only the owner may manage a role at or above their own top role.
The verified and unverified roles accepted any role of the server, and /verify then gives it to everyone who verifies, so someone with Manage Server could have the bot hand out Administrator. A newly chosen role is now checked like the bot's /settings set verified: no role with moderation or administration permissions (the bot's DANGEROUS_PERMISSIONS, from jarvis-core), nothing managed or at or above the bot's top role, and, unless they own the server, nothing at or above the person's own top role. An unchanged role is not checked again, so it does not block saving the rest. parse_form refuses every role if no check is given.

A field missing from the form used to delete its setting, and a stored channel or role that Discord no longer listed was silently cleared on the next save. Only submitted fields are changed now; the page shows unlisted stored IDs as "Unknown channel/role" options so they survive a save unless "Not set" is chosen, and multi-selects carry a blank marker so emptying one is still possible.

Saving used the first of any duplicate Setting rows and rewrote the whole document. It now writes the value to every row for that (guild, setting) with update_many and upsert, or deletes them all, and the page shows the newest row.

GuildContext carries the bot's user ID and can work out top roles and role problems for the person.
The bot acts with its own, usually much higher, role, so a request from the website could kick, ban or time out someone ranked at or above the moderator who asked. Before queueing, the target's top role is now compared with the person's (unless they own the server) and with the bot's, as Discord itself would; the owner can never be targeted. Someone who is not in the server has no roles, so banning them by ID still works, and warnings and unbans are not hierarchy-bound.
Adding a role to a rolegiver group checked the bot's rules but not Discord's own: a manager could let members pick up roles ranked above the manager themselves. The check is now the same role_problem() as the verified role (the bot's rules, plus nothing at or above the person's top role unless they own the server), and the page marks such roles as not offerable.
The bot tries every pattern of every filter on every message, and nothing limited how many a server could save, so a server could make each message cost the bot as much as it liked. Saving a filter now refuses to take the server past MAX_SERVER_PATTERNS (100) across all its filters, counting the new patterns in place of the old ones; if a save at the same moment takes it over anyway, the save is undone and refused. The filter is written with one keyed update (and upsert) rather than a whole-document save.

The tester matched patterns in the request's own thread, so a few slow patterns held up every other request in that process. It now runs in a worker thread, at most four at once, and within an overall budget of half a second; patterns left when the budget is spent are reported as not tried.
Approving and denying read the appeal, checked it was pending and then saved it, so two moderators at once could both decide it, and approving queued the unban before marking the appeal. The decision is now one find-and-update on status "pending"; only the moderator who wins it gets a 303, the unban request is inserted after the claim, and if that insert fails the appeal goes back to pending.

Two submissions at once could both pass the "already pending" check. After inserting, the earliest pending appeal for that server and person stands and any later one is removed and refused (no unique index is needed in jarvis-core).

/appeals asked the database again for every server the person was banned from (the setting, the ban, their appeals). It now reads the bans, the servers taking appeals and the person's appeals once each, and works the state out from those rows.
Cases, reminders, tags, autoreacts, role-ping bypasses, pinboards, autopurge delays and role groups were edited by reading the document, changing it in Python and saving all of it, which put back whatever the bot or the tasks service had written in between (a case action or note from Discord, a tag's use count, a reminder's delivery state). webui/updates.py sends just the change ($set, $push, $pull, $addToSet) keyed on the document's ID, optionally only while a condition still holds:

- a case note is pushed only while the case is open (422 if it was closed meanwhile); closing and reopening only set "open";
- a reminder edit sets message, time and repeat for the owner only (404 if it was sent and removed meanwhile);
- aliases, reactions, bypass users and group roles are pushed only while the list still has room and lacks the item, so a stale read cannot overfill it.
Deleting and then inserting left a moment with no reason or no rule (the bot could read it then), and a failure between the two lost it. A reason with the same name is now updated where it is; a rule is set with one update_many and upsert keyed on (guild, warnings), which also brings any duplicate rows for that number of warnings into line.
Cancelling deleted an announcement whether it was waiting or already being posted ("sending"), so the tasks service could post it anyway and its record and result were lost. The delete now matches only status "active" in one find-and-delete; one that is being sent or was sent stays, and the person is sent back with "Too late to cancel". The page shows "Posting now" instead of the Cancel button for those.
Every change to a role group queues a refresh_menus request in the person's name, and those counted towards the ten requests a minute, so editing a group could lock a moderator out of acting for a minute. The limit now counts only what the person asked for.
Deleting your data on /me/data ended only the session it was done from, and an operator's erase from the admin pages ended none, so web_sessions (user ID, name and server list) outlived the erasure. Both now delete every session of that person.
ZoneInfo() was given whatever the form sent, which it treats as a path under the zoneinfo directories, so odd names reached the file system and some raised errors other than the ones caught. A name must now be one of zoneinfo.available_timezones() (read once) before ZoneInfo sees it; anything else is a 422.
When Discord failed while a section, a table refresh or a search was loading, the handler rendered the full error page, navigation and all, as the answer to a request that only wanted a part of a page. An HX-Request now gets a short alert (still a 502, so the page script marks a lazy section as failed); a browser asking directly still gets the full page.
WEBUI_FORWARDED_ALLOW_IPS defaulted to "*", so anyone who could reach the port directly could claim any client address and scheme. It now defaults to 127.0.0.1; a proxy elsewhere (in Docker, the network's gateway or subnet) has to be named. The README, DEPLOY.md and sample.env say how.

When WEBUI_PUBLIC_URL is https (the same switch as the secure cookies), every answer carries Strict-Transport-Security: max-age=31536000, so a browser does not fall back to plain HTTP. The header code moved out of the middleware into add_security_headers().
Unused imports dropped, dict.fromkeys and list() where ruff asks for them, and the deliberately confusable Arabic-Indic digits written as \u escapes so RUF001 needs no exemption; the tests themselves are unchanged.
jarvis-core owns the shared collections, so the website cannot add unique indexes there. It now has its own small web_locks collection, whose documents are keyed by _id (always unique, so no index is needed beyond a TTL on expires_at):

- claim("appeal:{guild}:{user}"), claim("tag:{guild}:{name}") and claim("rolegroup:{guild}:{name}") are held while checking that the thing does not exist yet and creating it, so a burst of identical submissions makes exactly one. A second request waits up to five seconds for the claim and then gets a 409; a claim whose holder died lapses after a minute and is taken over. This replaces the appeal de-duplication after insert.
- The ten-requests-a-minute action limit was count-then-insert, so a burst got 13 to 17 through. It is now one atomic find-and-update counter per person ("rate:{user}"), whose window starts with the first request; menu refreshes still do not count.
A few characters were enough to hurt the site: (a{3001}){1000} adds about 700 MB that stays and holds the event loop for most of a second, and (?:(?:(?:a{100}){100}){100}){100} takes about 24 seconds to compile. Saving compiled every pattern on the event loop before the cap was even checked, and the tester's time budget did not cover compiling.

webui/patterns.py reads each pattern with a small tokenizer (escapes and classes skipped as units, groups and quantifiers followed) and refuses it, without compiling, when it is longer than MAX_PATTERN_LENGTH (200), has a counted repeat over MAX_REPEAT (100), nests quantified groups more than MAX_QUANTIFIED_NESTING (2) deep, multiplies nested counted repeats past MAX_REPEAT_PRODUCT (1000), or uses fuzzy matching or (?V1) set operations. These are the bot's rules and limits from jarvis/utils/filters.py.

Saving now checks every pattern first and names the one refused and why, then, holding a per-server claim, checks the 100-pattern cap, and only then compiles, in a worker thread under the same semaphore as the tester. The tester refuses such patterns as "not allowed" and matches with concurrent=True so the GIL is released. When a server is already at or over the cap, the error says how many patterns the other filters hold and how far to cut them.
jarvis-core's pinned DANGEROUS_PERMISSIONS leaves out permissions that are just as unsafe on a role the bot hands to everyone (Manage Nicknames, Manage Threads, Mute/Deafen/Move Members, Manage and Create Expressions and Events, View Audit Log, Priority Speaker, Pin Messages, Bypass Slowmode). webui/perms.py now defines the bot's full mask, 6782915044319678, and role_problem() refuses any role carrying it, as well as applying core's checks. A role whose permissions Discord did not give is refused rather than crashing.

Choosing a role the bot will hand out (verified, unverified, a role group's roles) now also needs Manage Roles, as the bot's own commands do; administrators and the owner have it implicitly. A role that is stored and sent back unchanged is not checked again. The roles page marks roles that fail any of this as not offerable.
Removing a timed-out member's permissions stopped moderation, but anything open to every member, such as creating, editing, aliasing and deleting tags, still worked. Access now says when the member is in a timeout (and not an administrator), and every state-changing request to a server's pages is refused with a 403 that says why; reading still works.
htmx does not swap 4xx and 5xx answers, so the small "Discord is not answering" fragment never appeared; the section kept its spinner or old content. An htmx:beforeSwap handler in static/app.js now swaps an error answer in when it is HTML. JSON errors are still left to the lazy-section handler, and nothing inline is added, so the Content-Security-Policy is unchanged.
Older versions stored channel and role IDs as strings. The "sent back unchanged" comparison was against the raw value, so an unchanged "201" was checked as a new choice (and refused if Discord no longer listed it), and the page did not mark string IDs in a multi-select as selected, so saving cleared them. Stored IDs are now read with parse_snowflake (each one, for lists) before comparing, and the page compares as strings.

A number the bot stored outside the page's range (a mass-mention limit above 250, say) is kept when it is sent back unchanged instead of failing the whole save.

Where duplicate rows of a setting disagree, none of them counts as "unchanged": the choice is checked afresh, so an ID only one stale copy holds cannot slip through.
The bot's /announce remove deletes an announcement that is waiting or being posted, and the tasks service only writes back to a claim that still exists, so deleting is safe. The website now does the same for a repeating announcement that is being posted (that post may still appear, no later one will) and shows Cancel for it. A one-off being posted is left alone, since deleting it would stop nothing and lose its result; the person is told it is being posted right now.
Heartbeat.find_all() validated every document at once, so a single heartbeat written by another version (a missing or odd field) made the whole overview a 500. The overview now reads the raw documents, validates them one at a time, and skips and logs (field names only) any it cannot read. jarvis-core's own helper for this is not in the pinned version.
A time in year 9999 or year 1, read in a zone that pushes it past the edge of the calendar, raised OverflowError (a 500) on both create and edit; it is now "That date is too far away". The list page falls back to UTC for such a stored time.

Editing a reminder the tasks service had already sent reported success while changing a reminder that would never fire again. The edit now only matches a reminder that is still active: a sent one is a 422 that says so, and one that is gone is a 404. QA's test for this case now expects the 422.
Saving a pinboard's automatic pinning with the emoji field left blank wrote the emoji back from the copy read moments earlier, undoing a change made in Discord meanwhile. Only the fields that were submitted are set now.
The role-hierarchy checks compared against the member whose ID is WEBUI_CLIENT_ID, the application ID, which is not always the bot user's. DiscordAPI.bot_user_id() asks /users/@me with the bot token once and remembers it, and GuildContext uses that.

A guild list entry whose id is not a Discord ID crashed int() with a 500; it is now a DiscordError, so the page says Discord is not answering properly (502).
Warnings asked for on the website had no hierarchy check, so a moderator could warn their equals and betters. Like the bot's /warn, a warning now needs the person to outrank the member (unless they own the server) and can never target the owner; the bot does not need to outrank them, since a warning is only a record.
Starlette answers an error nobody handled in its outermost middleware, outside the one that adds the Content-Security-Policy, X-Frame-Options and the rest, so a 500 went out without them. A catch-all handler now answers with a short page and adds the same headers; Starlette still re-raises the error afterwards, so it is logged as before.
(?x) made the regex module skip whitespace inside braces, so (?x)(a{3 001}){1 000} (about 700 MB) and (?x)(?:(?:(?:a {100}) {100}) {100}) {100} (about 24 s to compile) read as harmless to the validator, and (?#...) comments could split a repeat from its group the same way.

The static rules, identical to the bot's jarvis/utils/filters.py at bed79de:
- inline flags may only be i, m and s, globally ((?i), (?im)) or scoped ((?i:...)); x, V0/V1, a, L, u, a minus and anything else are refused, as are (?1) and (?R);
- (?#...) comments are refused;
- a brace body of ASCII digits, commas and whitespace is a counted repeat, read with the whitespace removed, and every number in it must be at most 100;
- unchanged: at most 200 characters, quantified groups nested at most 2 deep, nested counted repeats multiplying to at most 1000, no fuzzy matching.

Behind them, a pattern is compiled once in a separate, freshly spawned interpreter (python -I, never a fork of this threaded process) that limits itself to 256 MiB of address space (RLIMIT_AS) and 2 s of CPU (RLIMIT_CPU), and is killed after 3 s of wall-clock time. Running out of any of them, or dying, refuses the pattern with the reason; the verdict is kept in a 4096-entry LRU per pattern string. 256 MiB, not 512, so the probe alone also refuses patterns such as ((a{100})(?#c){100})(?#c){100}, which need about 290 MB. Saving probes every pattern before compiling it here; the tester probes within a 5 s budget, compiles with cache_pattern=False, and calls regex.purge() afterwards, as saving does, so nothing tried stays in memory.
The beforeSwap handler swapped any HTML error answer into its target: one 502 replaced the polling requests table (so polling stopped) or the member-search target (so later searches failed), and in offline mode the whole offline page landed in small sections.

The server now marks its own error fragments with X-Jarvis-Fragment: error and HX-Reswap: innerHTML (Discord not answering, an unhandled error, offline mode), and the page script swaps in only answers that carry the marker, inside the element, so the element and its htmx attributes stay. Offline mode answers an htmx request with such a fragment (503, Retry-After 60) instead of the full page, and an unhandled error in an htmx request gets one too, still with the security headers.
A request cancelled while holding a claim (the client went away) could skip the release and leave others waiting until the claim lapsed after a minute. The release now runs in an anyio CancelScope with shield=True, and a claim lapses after 15 s instead of 60, far more than any holder needs.

Waiting for a claim polled twenty times a second. It now waits 20 ms, doubling up to 0.5 s, each wait jittered to between half and all of that, and never past the deadline.

anyio is declared as a direct dependency (>=4.16.0,<5, the version already locked through Starlette and httpx) now that the code imports it.
Creating, editing and deleting tags and their aliases was open to every member with no limit, so one account could churn the tag list (and the claims behind it) as fast as it liked. Each change now counts against an atomic per-person counter (the same as the action limit) and the 21st in a minute is a 429.
A channels setting (log_ignore, lockdown_exclude) stored as one value rather than a list, by hand or by an old version, made the page's multi-select loop over a number and fail with a 500. Such a value is now shown, and compared when saving, as a list of one.
A refusal now names the Discord permission and the server, and points at Refresh the list from Discord for someone who was just given it. An expired CSRF token says the page was open too long.
?notice= and ?saved= put any text into the official notice box, so a link could say anything. Redirects now name a message by key (?notice=settings_saved); a few sentences take a plain name or a number in quotes. Unknown keys and the old ?saved= show nothing.
A 422 on settings, cases, actions, saved reasons and filters re-renders the page with status 422, the submitted values, a focused alert summary, aria-invalid on the fields and aria-describedby to their messages. The action form has a field group per action with the unit in the label, a button named for the action, and a confirmation naming action, target and reason. Opening a case for someone who has one open goes to it. Reasons can be loaded for editing and say when they replace one; the filter tester shows 429 and 422 in its result area. Other errors use a plain page with Go back and Your servers. Settings with nothing changed leave no audit entry. The audit trail shows setting labels and channel and role names.
Pressing Enter in the shared note field approved the appeal and unbanned the person. Approve asks for confirmation naming the person and the server.
Focus outlines were clipped by clip-path; field borders reach 3:1; the top bar stops following on a phone and the server tabs scroll in one row; grids no longer overflow narrow screens; each server page's h1 is its purpose with the server as a link above it; navigation entries are renamed for what they show. The made-up online lights and 'all systems nominal' are gone, and the offline screen says the dashboard is down for maintenance.
Each destructive button carries its own data-confirm wording (the generic Are you sure is gone); repeated Remove, Save, Allow, Edit, Delete, Records and Act buttons say which item they are for; times are <time> elements the page script shows in the viewer's zone with UTC in the tooltip; case and log tabs and pagers are labelled navigations; the moderator table shows zeros and names its rows; the request tables sit in a live region.
A wall-clock timeout, or a probe process that could not be started, depends on
how busy the machine is, so those are refused but asked again next time. A pass,
an invalid pattern, the memory limit and the CPU limit are remembered, in a
cache of 16384 patterns.
- the polled requests table is no longer a live region; a visually hidden status
  line says when a request is done or failed
- Cancel post keeps its visible text in its name, with the due time localised
- a 429 on Take action shows the form again with what was typed
- the action confirmation states the ban type and the length
- an unused length field no longer refuses a permanent or soft ban
- 403 messages list the permissions of every level that would have done
- confirmations fill only the placeholders the button declares
- notice refs are checked per key; case_exists says the note was not added
- Test patterns says when the test could not run
- the action button says Carry out action until a script names the action
chore: bump version to 3.2.1 and pin jarvis-core 3.2.1 (0c864d7)
All checks were successful
CI / precommit (pull_request) Successful in 33s
CI / test (3.13) (pull_request) Successful in 12m14s
CI / test (3.12) (pull_request) Successful in 12m20s
CI / test (3.15) (pull_request) Successful in 19m55s
CI / test (3.14) (pull_request) Successful in 20m2s
CI / image (pull_request) Has been skipped
CI / precommit (push) Successful in 27s
CI / test (3.12) (push) Successful in 9m2s
CI / test (3.15) (push) Successful in 8m45s
CI / test (3.13) (push) Successful in 14m35s
CI / test (3.14) (push) Successful in 14m31s
CI / image (push) Successful in 25s
5a42f65982
zevaryx deleted branch audit 2026-11-17 20:06:45 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
jarvis/jarvis-webui!1
No description provided.