Security audit #2

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

Lots of small bug fixes, nothing severe

Lots of small bug fixes, nothing severe
Moderators could act on members at or above their own highest role, and on
anyone below the bot, because the bot carried out the action with its own
higher role. One helper now applies Discord's rule (owner, or a higher top
role; never the owner; never at or above the bot) to the slash commands, the
Mute User menu and every website or alert-button action. A ban of someone who
has left needs no hierarchy check.

A website request from a moderator who is timed out is refused unless they
are an administrator, as Discord itself would.
The verified role is checked when it is set from Discord, but the website
could save any role, and roles can be edited afterwards. /verify now checks
the role again before the challenge and right before granting it, and tells
the member to ask an admin to fix the setting instead.
Every saved pattern was matched synchronously on the event loop for every
message, so a server could save enough slow patterns to stall the whole bot.
Matching now runs in a worker thread with the GIL released, each pattern keeps
its own timeout, a message gets 0.25 s in total, and only the first 100
patterns of a server are evaluated (logged once per server when more exist).
- Results are written with a conditional update on the claim (id, status
  "sending" and the original claimed_at) instead of save(), which upserted
  and brought back announcements cancelled while they were being posted.
  Releasing stale claims is conditional the same way.
- A claim is stamped with the time it is made, not the start of the run, so
  a long run cannot make its own later claims look stale.
- A repeating announcement that is too late or past its expiry is skipped
  and moved on (or finished) instead of being posted late.
- fetch_member returns None for someone who left (the library swallows the
  404), which now counts as Gone; the test fake does the same.
- The bot itself must hold Mention Everyone to ping @everyone, @here or a
  role that cannot be mentioned, or the ping would be silently dropped.
- on_command was a plain method, which interactions-py never registers, so
  the activity log never ran. It now listens for CommandCompletion, and the
  tests reach it through the client's registered listeners.
- The version statistic was written before the background tasks were
  started and outside their error handling, so a database error at startup
  meant no task ever ran. Tasks start first; the write is isolated.
- A Forbidden while fetching the activity log channel no longer deletes the
  setting; only a channel that is gone does.
One long reminder made Discord reject the whole autocomplete answer, so no
choices showed at all.
- Discord sends a message update when it adds a link preview. The text is
  unchanged and was already moderated, but the checks ran again and could
  warn or punish a second time. Edits whose content did not change are now
  ignored.
- Edit and delete log fields (message text, attachments, stickers) are cut
  to Discord's 1024-character field limit, so long messages are still logged.
- interactions-py runs the client's pre_run_callback (where maintenance and
  the blocklist are checked) only for commands, autocomplete and registered
  component callbacks, never for ButtonPressed or Select listeners. The
  bot's own buttons and role menus now make the same check first; buttons
  owned by paginators and wait_for_component are left alone.
- The delete button crashed in DMs, where the author is a User without
  server permissions and there is no guild. There, only the person the
  message was for may delete it.
- The moderation post-run hook runs after every command that returns, even
  one that refused or failed and said so; it then found the member's last
  recorded action and DMed and logged it again. Commands now call
  applied() once the action has really happened, and the hook does
  nothing otherwise (the manual-warning statistic included).
- The mute end comes from the command, not the member object, whose
  communication_disabled_until can still be None; without one the field is
  left out instead of crashing.
- A Forbidden while fetching the modlog channel keeps the setting; only a
  channel that is gone removes it.
- Test fakes for warn escalation gained the role positions the hierarchy
  check needs.
Purges may delete up to 1000 messages, but Discord's bulk delete takes at
most 100 IDs and interactions-py's delete_messages sends the list as given,
so any purge over 100 failed.
- The log was an unrotated jarvis.log in the working directory. It is now a
  RotatingFileHandler (10 MB, 5 backups) writing logs/jarvis.log, or
  wherever JARVIS_LOG_FILE says; the directory is created if missing.
- The owner's tail command reads the file backwards from its end instead
  of every line from the start, and log uploads the whole file only when it
  is under 8 MiB, otherwise its last 8 MiB from a whole line. Both read
  the file the handler actually writes, off the event loop, and report a
  missing or unreadable file instead of raising.
- logs/ is ignored by git.
calculate() ran on the event loop, so a heavy expression stalled the bot.
It now runs in a worker thread with a 2-second deadline. A thread cannot be
interrupted, and Python's big-integer powers hold the GIL while they run,
so powers whose result would exceed 1000 digits are refused before they
are computed. Long expressions and results are cut to fit the embed.
- BoundedInterpreter.visit_PowerNode evaluated both operands and then let
  the package's version evaluate them again, so a chain of N powers cost
  2**N steps; a short expression could pin a worker thread for minutes.
  The power is now computed from the values already worked out.
- Expressions are capped at 200 characters and 10,000 evaluation steps; the
  power-size check compares without converting huge exponents to float.
- /calc math runs on its own single-thread executor, so it can never use up
  the shared default pool that word filters run on, and has a per-user
  cooldown (5 per 30 s).
- A result over Python's 4300-digit printing limit is described instead of
  crashing the reply.
- The QA tower-of-powers xfail is removed; QA test lint (blind raises,
  unused loop variables) is fixed.
- The dangerous-permission denylist also covers Manage Nicknames, Manage
  Threads, Mute/Deafen/Move Members, Manage Expressions (emojis and
  stickers), Manage Events and View Audit Log. It gates the verified and
  unverified role settings, rolegiver groups and role menus, and every role
  the bot gives by itself.
- The rule for roles the bot gives by itself now lives in
  utils/permissions (auto_role_problem). On join, the unverified role and
  re-applied temproles are checked with it and skipped (logged) when unsafe.
- A cache miss for the bot's own member or the default role gives a clear
  "I can't see my own roles right now" refusal in the hierarchy check and
  the role checks, instead of a misleading message or an AttributeError.
- hierarchy_problem(bot_must_outrank=False) for warnings, slash and web: a
  warning is only a record. The QA hierarchy matrix and the web hierarchy
  test now expect that for warn.
- /temprole checks the hierarchy against the target unless it is the
  author themselves.
- The shared admin_or_permissions check refuses a timed-out member unless
  they are an administrator.
- Word filters run on their own four-thread pool instead of the shared
  default executor, and one server can have at most two messages being
  matched at once, so no server can occupy every worker.
- The deadline is set when the check is asked for, so time spent waiting for
  a slot or a worker counts against the 0.25 s budget.
- Patterns are compiled once and cached (bounded LRU, keyed by pattern
  text, so identical patterns in different servers share an entry).
- Still fail-open (a timeout is never a match), but every budget overrun
  and every job that timed out waiting for a worker is logged with the guild.
- applied() now takes the record the command saved and starts the logging
  at once in the background (errors logged, never raised). The post-run
  hook and its per-interaction dict are gone, so nothing leaks, and a later
  error in the command (escalation refused, say) no longer loses the log.
  The case and modlog use that record, so a softban (saved inactive) is
  posted and a case never points at an older action.
- Guild.fetch_channel returns None for a channel the bot may not read as
  well as for a deleted one (the library turns Forbidden into a placeholder).
  The modlog and activity log now ask Discord directly when the channel is
  not cached, and remove the setting only on a 404 or a channel of another
  server.
- /ban and /kick (slash and website) still DM before acting, since a banned
  user often cannot be messaged afterwards, but first check what can be
  checked: the hierarchy and that the bot holds Ban/Kick Members. A
  refusal there sends no DM. Discord refusing after the DM is not
  pre-checkable; the QA DM tests were changed to this pre-check
  requirement (the bot lacking the permission) instead of a Forbidden from
  Discord.
- /mute refuses durations of zero or less.
- A purge records what it deleted in a finally, so a batch failing part way
  still leaves the earlier deletions in the audit trail.
- QA xfails removed for the modlog-with-the-real-Guild, mute duration, DM
  and purge tests.
Without the original in the cache, an edit was always moderated, so the
update Discord sends when it adds a link preview warned again (roleping and
massmention warnings do not delete the message). Such an update has no
edited timestamp; a real edit has one and is still moderated. The tests now
give real edits a timestamp, and the QA unfurl xfail is removed.
Choices were keyed by their label, so two reminders with the same text made
in the same second (a repeat and its copy) collapsed into one. They are now
keyed by the reminder's ID. QA xfail removed.
- interactions-py runs the pre-run callback before autocomplete but never
  the command's checks, so anyone could see what a moderator command
  suggests (saved reasons, active bans, cases). Autocomplete now answers
  with no suggestions when maintenance, the blocklist or the command's own
  checks (and its extension's) say no; cooldowns are not touched. The
  deliberate refusal is not logged as an error.
- Alert quick actions (mute, kick, ban) run through the website's action
  machinery, so the web_actions switch now turns them off too; dismissing
  still works.
- The owner's tail and log commands DM their output instead of posting it
  in the channel they were typed in; the log holds user IDs, message text
  and errors. With DMs closed, the channel only gets a note to open them.
- If logs/ (or JARVIS_LOG_FILE) cannot be written, the problem is printed to
  stderr and the bot carries on with console logging instead of failing to
  start.
The dangerous-permission denylist now also covers Pin Messages, Bypass
Slowmode, Create Expressions, Create Events and Priority Speaker. The final
bitmask is published as DANGEROUS_PERMISSIONS_VALUE = 6782915044319678 for
the website to mirror; a test keeps it equal to DANGEROUS_PERMISSIONS.
Discord only lets someone with Manage Roles assign roles, but Manage Server
alone could set the verified and unverified roles and add rolegiver roles,
which the bot then hands out for them. Those commands (and the bulk
rolegiver add) now also require Manage Roles; the owner and administrators
pass.
Compiling a regular expression is covered by no timeout: (a{3001}){1000}
takes about 0.76 s with the GIL held and leaves ~700 MB in regex's cache.
A small tokenizer (escapes and character classes read as units, groups,
quantifiers and braces followed) now refuses, before any compile, a pattern:
- longer than 200 characters;
- with a counted repeat ({n}, {n,}, {,m}, {n,m}) over 100;
- with quantified groups nested more than 2 deep;
- whose counted repeats nested inside each other multiply to more than
  1000 (each counts by its largest number, *, + and ? as 1); without this
  ((a{100}){100}){100} still passes the other limits and costs 0.3 s and
  270 MB to compile;
- using fuzzy matching ({e<=1} and the like) or (?V1) set operations.

/filter refuses such patterns with the reason, and checks and compiles what
was typed on the filter workers. At match time, stored patterns over the
limits are skipped (one warning per server) and never compiled; compiling
happens only on the filter workers, with regex's own pattern cache off so
the bounded LRU is the only one.
str.isdigit() also accepts characters such as "²" that int() cannot read, so
pattern_problem("a{²}") raised ValueError instead of answering. Only ASCII
digits now make a counted repeat, as in the website's copy of the rules;
regex treats such braces as literal text too.
(?x) makes regex skip whitespace inside braces, so (?x)(a{3 001}){1 000}
(~700 MB) and (?x)(?:(?:(?:a {100}) {100}) {100}) {100} (~24 s) passed the
static rules, as did repeats split from their group by (?#...) comments.
The rules are now the website's (webui/patterns.py), identical on a
3000-pattern differential run:
- inline flags only i, m and s, global or scoped; x, V0/V1, a, L, a minus
  sign and anything else are refused;
- (?#...) comments are refused;
- a brace body of ASCII digits, commas and whitespace is a counted repeat,
  read with the whitespace removed, in any mode.

Whatever the rules miss is caught by a probe: before this process compiles a
pattern for the first time, a fresh isolated interpreter (python -I, spawned,
never forked from the threaded bot) compiles it under RLIMIT_AS 256 MiB and
RLIMIT_CPU 2 s with a 3 s wall clock; running out, crashing or timing out
refuses the pattern. 256 MiB rather than 512 so the probe alone refuses the
~290 MB patterns from the re-test. Verdicts are cached per pattern (LRU of
4096). /filter probes what was typed before compiling it; stored patterns
are probed on the filter workers the first time they are needed, and those
refused are skipped with one warning per server.
Compile probes (one python -I process each) ran on the 4 matching workers,
outside the per-server slot, with no timeout and no sharing between callers:
one server saving 100 new patterns and sending a burst queued thousands of
spawns, every server's find_match timed out, and filters failed open.
- Probes have their own pool of 2 threads, so matching never waits on them.
- Concurrent callers share one in-flight probe per pattern (shielded, so a
  caller giving up does not cancel it for the others).
- A server runs one probe at a time, so it cannot take the whole pool.
- A message waits for unprobed patterns at most PROBE_WAIT (1 s); those not
  done are skipped for that message, and the verdict is kept when it lands.

Probe verdicts now match the website's copy (webui/patterns.py, 1b33d36):
- a bounded LRU of 16384 (was lru_cache of 4096, which 100 patterns in over
  40 servers overflowed), with clear_probe_cache();
- only settled verdicts are remembered: OK, invalid, memory limit, and the
  CPU limit (SIGXCPU; the child now sets RLIMIT_CPU soft below hard, as with
  soft == hard the kernel sent SIGKILL and the CPU verdict was never seen);
- the wall-clock timeout, an OSError at spawn (EAGAIN, ENOMEM, no fds), and
  any other exit without a verdict refuse the pattern for now only ("could
  not be checked"); an OSError no longer escapes into on_message or /filter.
The compiled-pattern cache no longer keeps a for-now refusal either.

The message handler caps to the first MAX_PATTERNS non-blank patterns
before the static check, which is now cached, instead of checking every
stored pattern on the event loop. /filter refuses more than MAX_PATTERNS
lines before probing any. The swapped attribute docstrings of
_filter_refused_warned and _filter_probe_warned are fixed.
/filter create and /filter edit had no server-wide limit, so a server could
store any number of patterns that the bot then considered on every message.
They now refuse a save that would take the server's filters over 100
patterns together (not counting the filter being edited), with the
website's wording, one save per server at a time.
The last Guild.fetch_channel in log_channel was outside the try: it catches
only NotFound, so a Forbidden or a server error from Discord escaped. It is
now treated like the first request's errors: the channel cannot be used now,
and the setting is kept. The docstring says which errors reach us.
The record callback runs in a finally; if it raised, its error replaced the
one that stopped deleting. It is now logged and swallowed, so the real error
reaches the caller.
- /filter defers its modal answer (privately) before checking: probing about
  40 or more new patterns took longer than Discord's 3 s, so the reply failed
  and the save was lost. Every later reply is a follow-up.
- After startup a background task probes the patterns of every server the
  bot is in that has filters (capped and through the static rules, as for
  messages), one server at a time through the same per-server probe path,
  so warming keeps at most one probe worker busy and shares probes with live
  messages. One info line per server: how its patterns settled, or how many
  are still pending after PROBE_WARM_WAIT (120 s).
- "Could not start the compile probe" is logged at most once a minute, with
  the number of failures since the last warning.
- probe_patterns tells refused-for-good (too costly to compile) from
  refused-for-now ("could not be checked yet"); the message handler reports
  the latter as such, at most once a minute per server, instead of calling it
  too costly.
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 41s
CI / test (3.12) (pull_request) Successful in 10m1s
CI / test (3.13) (pull_request) Successful in 15m51s
CI / test (3.14) (pull_request) Successful in 8m7s
CI / test (3.15) (pull_request) Successful in 8m2s
CI / image (pull_request) Has been skipped
CI / precommit (push) Successful in 28s
CI / test (3.12) (push) Successful in 7m58s
CI / test (3.14) (push) Successful in 8m3s
CI / test (3.15) (push) Successful in 8m5s
CI / test (3.13) (push) Successful in 13m37s
CI / image (push) Successful in 8s
b8dd0b645d
zevaryx deleted branch audit 2026-11-17 20:06:54 +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-bot!2
No description provided.