Skip to content

Security fixes for citry 1.3.0 - #881

Merged
JuroOravec merged 50 commits into
mainfrom
security/1.3.0-fixes
Nov 25, 2026
Merged

JuroOravec merged 50 commits into
mainfrom
security/1.3.0-fixes

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

(Opus 5.5)

Security fixes for citry 1.3.0, built in three private security advisories. The advisories will be published after 1.3.0 is on PyPI; their text gives the details, so this description stays short.

  • Events guards: _guard, _context and _csrf (and @event(guard=..., csrf=...)) must be plain functions; an async def or other awaitable one is refused when the class is defined. A component's _guard and a handler's own guard both run. A guard result that means "no" refuses the call, a returned function answers 500, and stacked @event decorators are refused.
  • Deeply nested event data on PyPy: Citry's nesting limit now counts the levels where Pydantic calls back into Python, and refuses at definition the few schema shapes it cannot bound on interpreters other than CPython.
  • One combined v1.3.0 changelog section, with the docs, design docs and trust-boundaries rows these changes touch.

The fixes merged current main (including #875) in a chain, so this branch has main as an ancestor; merging it with a merge commit keeps every fix commit's hash. CI has never run on these commits, because GitHub Actions does not run in the private forks. Local evidence on the tip:

  • citry and citry_lsp tests: 17,384 passed, 0 failed
  • ruff, mypy (macOS and --platform linux), scripts/validate.py, docs build-check --strict: clean
  • Chromium e2e: 639 passed; 1 failed (test_preview_e2e, which needs full Chromium where only the headless shell is installed)
  • PyPy 7.3.23: 269 passed; 2 failed, both known and also failing on the base commit

Versioning: these are security fixes. Some refuse code 1.2.0 accepted, and the changelog says which; they ship in the 1.3.0 minor release with the other 1.3.0 changes.

🤖 Generated with Claude Code

JuroOravec and others added 30 commits November 24, 2026 13:23
PyPy lets a thread use only as much stack as its recursion limit sets,
whatever the thread's real size, and ends the process when compiled
code runs out of it. On interpreters other than CPython, the nesting
limit now counts every Python function that Citry's copy of a
validator calls on the way down (Pydantic's own wrap functions and
Citry's wrappers for discarded parts and the work budget), and check
threads apply the small-stack limit of 32 levels. CPython keeps its
current rules and limit.

Tests set the rule on CPython, so CI covers it; the depth-dependent
tests read the limit for the interpreter they run on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Citry calls an event guard, the _context function and the _csrf
function without awaiting them. Refuse an async one (and a generator,
a partial of one, or an object whose __call__ is one) when the
component class is defined, as _csp_nonce and _render_inputs already
do, and refuse a call whose guard, _context or _csrf function still
returns a coroutine. _csp_nonce and _render_inputs now use the same
check, which also catches an object with an async __call__.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No wrapper counts the levels of a class that Pydantic reads from
`Json[...]` text, and each JSON string starts a fresh parse, so on
interpreters other than CPython a `data` class or writable State field
that reaches such a class is refused when the component is defined, as
for a State that Citry reads only as JSON.

The tests that raise the nesting limit for work-budget checks now do so
only under the PyPy rules, so on CPython they keep testing the real
limit. Docs gain an "Event data on PyPy" section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…run code

A _context value is app data and may be another awaitable or a
generator on purpose, so only a coroutine is refused there. Close only a
coroutine or generator, never an app object. Clearer error messages, a
docs note on decorators that call an async guard, and the trust
boundaries rows for guards, _context, _csrf and _render_inputs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A handler's @event(guard=...) now adds to the component's _guard (or
the engine default _guard when the component sets none) instead of
replacing it: the dispatcher runs _context, the component-level guard,
then the handler's guard, and either one refuses the call. A handler
that must be more open than its component opts out with
@event(component_guard=False). The same function set at both levels
runs once.

Docs: security.md, advanced/web-frameworks.md, the design doc, the
trust boundaries table and the @event docstring describe the order and
the opt-out; CHANGELOG.md says which calls are now refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… guard docs

Only component_guard=False skips the component-level guard, so an
options record built with a falsy stand-in still runs it. Tests cover a
component guard that crashes and that case.

Docs: security.md shows how to set an app-wide guard, says a
component's _guard (even None) replaces it, that the opt-out skips the
app-wide guard too, and what still runs. The design docs and trust
boundaries table name the other ways a guard is skipped (_guard = None,
an on_event hook that answers). Wording fixes in the changelog,
docstring and comments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Under the PyPy rules, a NamedTuple that can hold itself inside
`Json[...]` now counts as a recursive class, and any type that holds
itself again inside `Json[...]` text is refused too, whatever its kind:
each JSON string starts a fresh parse, so strings nested in each other
let the data choose the depth of a tuple or list as much as a class.
CPython keeps its rule for a State read only as JSON.

The refusal now names the field where the outermost `Json[...]` above
the refused part is written, so its plain-type advice points at a field
the author can change, and the wrap-validator advice says a strict class
then refuses dates written as strings.

Tests cover the NamedTuple and the tuple alias, the field the message
names, a wrap-validated recursive class being accepted and counted, the
check at the first call, and a State finished after registration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The changelog names the remaining limits and the way out, says the
rules apply on every Python other than CPython, and separates the
definition-time ValueError from the 422. The security and compatibility
pages list what counts as an extra level, the definition-time refusal
of a type that loops through `Json[...]`, and how a wrap validator
changes what a strict class accepts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The PyPy section now starts with what goes wrong, defines a level and
gives the extra levels per part. The Json[...] bullet moves to the end
of the refused-schema list, keeps its sub-items inside the list, gives a
wrap validator example, and says that declaring the field with the type
inside Json[...] makes it take the value itself, not JSON text, which
the error message now says too. The changelog says which releases are
affected, that the app fails at import, and links the docs section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on text on PyPy

A wrap validator counts its own levels, not those of a recursive type
inside the Json[...] text below it, and each JSON string adds up to 200
uncounted levels. So a model with its own wrap validator whose Json[...]
field held a recursive tuple that held the model again, a wrap validator
only around the Json[...] member, or two different recursive types each
inside the other's text still ended PyPy. Under the PyPy rules, a
recursive type reached inside Json[...] is now refused when its value
can hold Json[...] text whose type has an uncounted loop, following
every reference, past wrap validators too. A recursive type that cannot
reach more such text, such as JsonValue, stays accepted.

The refusal names the recursive type that needs a wrap validator of its
own, and the docs, changelog and design doc say that a wrap validator
elsewhere does not count those levels. CPython is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A guard refused a call only by raising EventError, so a guard that
returned False (such as `return user.is_staff`) let every call through.
The dispatcher now reads each guard's result in one place,
_apply_guard_result: False from the component guard, the engine
default or the handler's own guard answers 403 `forbidden`, as if the
guard had raised, and any other value except None lets the call go
ahead with a warning that names the guard and the component. The
warning shows the result's type, never its value.

Every route runs guards through _prepare_call, so the batch and
per-event routes, the form post, ViewEvents and both dispatch paths
apply the same rule; tests cover each.

This refuses calls that 1.2.0 let through, as part of the security
fix; the v1.3.0 changelog entry says so. Docs: security.md, the
@event docstring, trust_boundaries.md and the events design doc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The warning names the result's type as "a value of type 'int'", the
error for an async guard no longer reads as if returning None refuses,
and the security guide says to return False explicitly, since
`user and user.is_staff` gives None, which lets the call go ahead. The
changelog lists the False rule as its own entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n PyPy

One JSON string lets Pydantic nest up to 200 levels that Citry does not
count, and those come on top of the levels checked outside the string.
On PyPy a list alias 198 levels deep in one string ended the process
below 31 counted models, and below an uncounted tuple alias outside
Json[...], as event data and as a State write. So under the PyPy rules
any recursive type inside Json[...] without a wrap validator of its own
is refused, pydantic.JsonValue included; Json[Any], which Pydantic only
parses, stays accepted and passed the same requests.

The docs, changelog and error message point to Json[Any] for free-form
JSON and give the measured counts per part. CPython is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…w nits

A Cython or mypyc coroutine registers only as collections.abc.Coroutine,
so _context now refuses any Coroutine, not only a native one. Close only
a coroutine or generator whose code has not started, and word the error
for any result Citry would have to await or iterate. The security page
now says a decorator on a guard must run any async function it calls to
the end, and the trust boundaries rows cite current line numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the review fixes of the async-guard branch (a compiled
coroutine from _context is refused, only unstarted code is closed, the
decorator note on the security page). The conflict in the trust
boundaries table keeps this branch's guard row with the new wording and
takes the other branch's CSRF row; the cited line numbers in both rows
and the _render_inputs row match the merged code. The _apply_guard_result
docstring now lists every result refuse_deferred_result refuses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d docs with one _guard

A second @event(...) on a handler replaced the settings the first one
stored, so an inner guard= never ran. @event now raises ValueError at
decoration when the function, or a function down its __wrapped__ chain,
already has @event settings, and names the handler. Applying @event once
and reusing the result in several Events classes still works, as do
subclass overrides and ViewEvents verbs.

The security page now shows first how one component _guard lets named
handlers through with self.event.name, which keeps every access rule in
one place, and warns that renaming a handler moves it to the stricter
rule. @event(component_guard=False) follows for an occasional public
handler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The PyPy rule for recursive types inside Json[...] followed the Python
part of a json-or-python node, which a JSON read never takes, so it
refused Json[pydantic.JsonValue], which reads JSON as Any. It also
refused a recursive type in a State read only as JSON, where the rule
for any type does not apply because no Json[...] text is involved. The
loop graph under the PyPy rules now follows only the JSON part, and the
rule for any type applies only below a Json[...] field.

The docs, changelog and design doc say that a free-form field deep
inside a schema with many validators can still end PyPy, as in 1.2.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The refusal for a guard, _csrf or _context result now tells the author to
write a plain def that returns no coroutine (or, for guards and _csrf,
no awaitable or generator), since a plain def can still return one. The
changelog names async generators, the comment says a compiled coroutine
is a Coroutine but not a native one, and the handler-name row in the
trust boundaries table cites current line numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the second round of review fixes on the async-guard branch.
The trust boundaries conflicts keep this branch's rows; their cited
line numbers match the merged code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… guard example

A decorator that keeps __wrapped__ but not the function's attributes left
an inner @event's settings where Citry never reads them, so its guard=
did not run. The component class now fails to load when a handler does
not carry the settings of a function down its __wrapped__ chain
(methods aside, which ViewEvents sets on the outer function).

The security page example returns require_login(self) from _guard, since
a guard that refuses by returning False refuses nothing when the caller
drops the value. The stacked-@event error and changelog name the case of
one function decorated again for another class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e silently

A guard that returns an EventError instance now refuses the call with
that error's status, message and field errors, as raising it does.
A guard that returns True lets the call go ahead without the warning;
other values besides None, True, False and an EventError still log it.
The returned error's traceback is cleared before it is raised, so an
error kept in a constant does not collect one traceback per call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s is created

The dispatcher read `detached` and `bundle`, and the browser manifest
read `latest_wins`, `bundle` and `detached`, from the function each time.
Decorating or editing a shared function after a class was created could
therefore change how that class's handlers behaved, for example turning
off the refusal of a raw response on the batch route. EventHandler now
carries these three settings, copied in `_compute_info` like the others,
and nothing reads `@event` settings from the function after that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Cython generator or async generator registers only with
collections.abc, so the inspect checks missed it and a guard that
returned one let the call through. Check the abstract classes instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/py/citry/citry/ext/events/handlers.py
… commits

Clear the traceback of an EventError a guard returns once its answer is
built, so a shared error does not keep the call's frames alive. The
route tests now tell a returned EventError from False by its message.
The warning, the @event docstring, the changelog, security.md and the
design docs describe the cases more exactly, and the trust boundaries
line numbers follow the code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, and count State serializers

On PyPy, a State that Citry reads only as JSON (strict, or a model that
forbids extra keys and has a field alias) accepted a recursive alias
such as Sequence[Sequence[Sequence[SS]]]. Nothing counts that JSON read,
so a 640-byte write 150 levels deep passed, and writing the State out
again (model_dump calls a Python function at each Sequence level) ended
the process. The PyPy loop rule now applies there to any recursive
type, as it does inside Json[...], and the refusal offers a lax State
as a fix.

Writing a State out also calls an app's WrapSerializer or
PlainSerializer at every level of a recursive value, including on plain
list levels the read does not count. A lax State with such a list alias
ended PyPy at 150 levels (as on 1.2.0). Under the PyPy rules, the copy
for a State now counts a level for each node with an app's serializer
function that leads into recursion. Pydantic's own serializers for
Sequence and defaultdict already sit on a counted node, and event data
is never written out, so neither changes. CPython is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The count from c5ee6ad missed a serializer written on a reference to
a recursive alias, as in Annotated[Tree, WrapSerializer(f)] inside Tree:
Pydantic puts it on the definition-ref node, which the copy does not
finish, so a lax State write 150 levels deep passed and ended PyPy when
the State was written out. It also left event data uncounted, and a
handler that stores checked event data in State as it is
(state.tree = data.tree) ended PyPy the same way.

Under the PyPy rules the copy now counts a level at a reference with an
app's serializer function too, and counts in every copy, event data
included. CPython is unchanged. A handler that stores data in a State
field of another type stays outside the count and is documented.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ents verb methods on the class

A guard that returns any exception or any false value other than None now
refuses the call. A returned EventError keeps its own status and message;
any other exception, or an exception class, answers the standard 403 and its
text never reaches the browser, and its traceback is cleared. False, 0, an
empty list or QuerySet and numpy.False_ answer 403. None and True allow
silently; any other true value allows with the existing warning. When
testing the value for true or false raises, the call answers handler_error
(500), as a guard that raises an unexpected error does.

ViewEvents no longer writes methods onto the handler function. The verb's
HTTP method comes from the class when the component class is created
(verb_handler_methods), so one function used in several classes gets each
class's own methods, and refuse_hidden_event_settings compares the whole
settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mmit

An EventError raised while testing a guard's result answers as raised,
rather than as a 500. Docs: the security page's opening list of ways to
refuse, "false value other than None" in the changelog, security page and
GUARD_PURPOSE, a note that Django refuses database queries in guards under
an async server, the design-doc guard row, the sentence about what Citry
writes onto a handler function (only @event does), and two line numbers in
the trust boundaries doc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
JuroOravec and others added 20 commits November 24, 2026 16:51
Adds a test that an app serializer wrapped in functools.partial is
counted, and corrects the docs and comments: a State read only as JSON
refuses any recursive type on PyPy because nothing counts its up to 200
levels, and only some types, such as Sequence[...], call Python at each
level when the State is written out. Event data counts serializers too
(c5ee6ad's message said otherwise; b1fbb11 changed that).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…name the failing guard

- A guard that returns a function or other callable (`return
  self.can_edit` without the `()`) now fails the call with a 500 and a
  log line naming the guard and the callable; it allowed the call with
  a warning before.
- A returned or raised exception's tracebacks are cleared down its
  `__cause__`/`__context__` chain and an exception group's members, with
  cycles visited once, so a shared exception does not keep a call's
  frames.
- The 500 log line names the step that failed before the handler ran
  (the on_event hook, Events._context, the component guard or the
  handler's guard by name, a State validator) and says the handler did
  not run.
- citry_lsp reads `detached` from the EventHandler, where citry copies
  the @event settings when the class is created, so editor hints match
  the dispatcher; it falls back to the function's options on an older
  citry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… serializer on PyPy

A serializer's return type (return_type=, a field_serializer's return
annotation, or the serializer Pydantic gives a PlainValidator) is the
schema Pydantic writes the returned value with. Citry's check reads the
field's own type, such as Any, so on PyPy a State value 190 levels deep
passed the check and ended the process when Citry wrote the State out
through a recursive return type whose levels call a serializer
function, as on 1.2.0. A handler that stored such event data in State
ended it the same way.

Under the PyPy rules, defining a component now raises ValueError when
its event data class or any State field, writable or not, has a
serializer whose return type leads into a recursive type with a
serializer function, or a PlainValidator on a recursive type. CPython
is unchanged. The docs list the remaining known limits: many
AfterValidators on one recursive type, and a handler that stores event
data in a State field of another type that has a serializer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Clearing tracebacks stops at the exception the host was handling when
  it called the dispatcher, so a host that dispatches inside an `except`
  block keeps its own traceback, and never raises, so an exception class
  whose chain raises cannot end the whole request.
- Naming a guard for the log cannot fail; the debug message says the
  step "failed with" an error, since a refused result raised nothing.
- The State validator log line names the State class.
- Docs: line references, the security.md paragraph split, plainer
  wording in events.md and the changelog, the test class docstring and
  the citry_lsp comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The error message for a PlainValidator now says that Pydantic writes the
value out through the recursive type, since the validator may sit on the
field rather than on that type, and the serializer message offers
annotating a field_serializer or model_serializer as returning Any. A
new test locks that a return type whose serializer cannot hold itself
is accepted.

The docs name the refusal of a PlainValidator on a level of a recursive
type, say that a recursive return type with a serializer only on a
value that does not nest is refused too, and list one more known limit:
a handler that stores, in a free-form State field, a Pydantic class from
a data class that is not itself a Pydantic class, such as a
standard-library dataclass. The AfterValidator limit gives the measured
count (25) instead of "25 or more".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ugh they do not end PyPy

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings main into this branch through the async guard fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings main and the guard fixes into this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e references

The PyPy section of the security page said raising the recursion limit
does not make the check safer. Measured on PyPy, the depth at which
nested data ends the process moves with sys.setrecursionlimit(), and
the 32-level limit was sized at the default of 1,000. Say that, and
advise against lowering it.

Point the trust-boundary rows for event data, CSRF names and State
writes at the current lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ions

The Component.Events docstring, which becomes the API reference, now
matches the class-definition check for these settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The API reference now says that @event(guard=...) runs after _guard,
names component_guard=False, and lists the guard results that refuse a
call. Also point the page nonce row in trust_boundaries.md at
_page_csp_nonce's current line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Write a v1.3.0 changelog intro that names every fix and warns that some
fixes refuse code 1.2.0 accepted, rewrap two entries, say which limit
not to lower in the PyPy section of the security page, and point two
trust-boundary references at their current lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also point the trust-boundary rows that the three fixes touch at the
current lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say that both guards run before the data check and that raising an
exception other than EventError fails the call with a 500, say the
guards get a shallow copy of the args, and point the page nonce and
guard rows in trust_boundaries.md at the current lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec merged commit 31bc11e into main Nov 25, 2026
34 checks passed
@JuroOravec
JuroOravec deleted the security/1.3.0-fixes branch November 25, 2026 03:38
JuroOravec added a commit that referenced this pull request Nov 25, 2026
… route for advisory fixes (#884)

Add public review records for GHSA-29wx-2wvw-8962, GHSA-gj9m-wwqx-m37j
and GHSA-2jch-pr4c-gf9m, published 2026-11-25, and for #875 (guards run
before the data check).

security.md and the Events design doc now say that reloading a module
that applies @event(...) to a function it imports raises the stacked
@event error. docs/codebase.md "Releasing advisory fixes" describes
landing the fix chain through a public pull request merged with a merge
commit (1.3.0, #881) as the preferred route, next to the fast-forward
push used for 0.7.0.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant