Repository navigation
fix: enforce relation databag read permissions on all access paths - #2738
tonyandrewmeyer merged 10 commits into
Conversation
A non-leader unit that touched its own application databag got a bare `ModelError: ERROR permission denied (unauthorized access)` from Juju instead of the `RelationDataAccessError` that ops already has for this case, because only `__getitem__` called `_validate_read`. Read paths that go via `_GenericLazyMapping` (`__contains__`, `__iter__`, `__len__`) reached the hook tool unvalidated. Validate in `_load` as well, so no read path can bypass the check. `__getitem__` and `__repr__` now only re-validate when the data is already cached, since otherwise `_load` does it; that keeps the current behaviour for a unit that loses leadership after a read without adding a redundant leadership check. Also check write permission in `update()` before reading the current content. Change detection reads the databag to skip no-op writes, and that incidental read was what failed first, so a follower writing application data got an error about a read it never asked for rather than one naming the write. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018mFLSaFNf7NmyUtrLjLp4q
Co-authored-by: Tony Meyer <tony.meyer@gmail.com>
| # The charm records every databag, including its own application one, so it | ||
| # needs to be the leader to read them all. | ||
| harness.set_leader(True) |
There was a problem hiding this comment.
This is because there's a behaviour change. You're allowed to access relation data outside of a hook in Harness without setting up things so that you should have access to it. This could break real tests. At minimum it would need a hyrum run, and I wonder that it's too risky to do at all in a minor / point release.
| # Always check permissions, and do so before reading the current content, so | ||
| # that a unit that can't write gets an error naming the write, rather than one | ||
| # about the read that change detection happens to require. | ||
| self._validate_write(data) |
There was a problem hiding this comment.
This is a behaviour change in that if there was something that was removed by the change but has type problems (something we can't store, for example) it will break now and wouldn't have before. I think in this case that's probably ok, it seems a weird situation and is arguably buggy behaviour anyway. But it would be worth checking that nothing we know of does break because of this.
There was a problem hiding this comment.
Makes sense, running hyrum before merge should hopefully cover it, and if not then as you say, it was arguably a bug on the user's part before anyway.
| # these probably fail at real runtime with a ModelError | ||
| # but pass here because the validation methods are only hooked up to get/set |
There was a problem hiding this comment.
The change here is exactly what this comment is about. Basically, the comment was acknowledging the buggy (or limited) behaviour and the test pinned that behaviour. The PR updates it so that we're doing the proper thing instead.
__repr__ guarded with _validate_cached_read(), which is deliberately a no-op when the data hasn't been loaded yet. For an unloaded databag the guard passed and the following super().__repr__() triggered _load() -> _validate_read(), so RelationDataAccessError escaped instead of repr() returning '<n/a>'. Force the load inside the same try, so the read is validated exactly once on either path (cached via _validate_cached_read, uncached via _load) and the error is caught. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AUVLD2hkQQdF5jjW12f3Hk
|
I think this does need a hyrum run to verify that nothing we know of breaks. I'm happy to do that, but would appreciate a review in advance to check that nothing else needs to change first, or in case we want to reject some of these changes without doing the run. |
`__contains__`, `__iter__` and `__len__` are served from `_data`, which only calls `_load` while the cache is empty, so a databag that loaded while the unit was leader stayed readable through all three after leadership was lost - the read/no-read split this change removes from the cold path, reappearing on the warm one. They now validate like `__getitem__` does. The check they pay for is a comparison against `is_leader`'s 30-second lease cache, not another hook-tool call. Validating inside `_load` also pre-empted the empty dict it returns for a relation Juju has already forgotten: `relation.app` is None on a broken relation, so a follower's `in`/`len()`/`iter()` raised "Remote application instance cannot be retrieved" where they used to answer False, 0 and []. The validation is now skipped for an inactive relation, in one place that both the cold and the warm path go through. While there: the local-app-databag guard moves above the remote-app type guard, so a follower reading its own databag is told that rather than told about a remote application it never mentioned (the peer check stays first, since peer data is readable). `_validate_read`'s docstring says it raises, which is what it does. `__repr__` returns inside the `try` instead of discarding a `_data` read to trigger validation. `test_relation_validates_access` asserted that `len()` and `in` succeed for a follower, with a comment saying they "probably fail at real runtime with a ModelError but pass here because the validation methods are only hooked up to get/set". That is the bug, so the minion half now expects the error. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
dwilding
left a comment
There was a problem hiding this comment.
I've reviewed your comments and broadly understand what the code is doing (but not every detail). My understanding is:
-
This change is very unlikely to break any charms in production. If a non-leader unit previously received a
ModelErrorwhen trying to access the application databag, it will continue to receive aModelError, just perhaps faster and with a more helpful error message.Technically we're changing the behaviour of
update()with a non-string key - raising instead of the call being a noop - which seems reasonable as a bugfix. -
Unit tests might break, but if they break after this change then they were already testing something unintended.
I think we need to see what Hyrum produces. If we're concerned at all about breaking any real unit tests, how about we give one month notice in release notes before releasing this? The unit test corrections are minimal and people can safely do the corrections before the release.
james-garner-canonical
left a comment
There was a problem hiding this comment.
Comment review as I wonder if the _check + _validate combo is 100% what we need. However the changes seem correct overall, and if I'm wrong about _check then they're essentially good to go as-is.
| # -- `relation.app` is None on a broken relation (see Relation.__init__ | ||
| # and LP#1960934), which is exactly when the two overlap. |
There was a problem hiding this comment.
Are these cross references helpful?
There was a problem hiding this comment.
I'll shorten the comment, because it does seem a bit wordy. But I think the reference is likely to be useful if people are digging into this in the future. Particularly since it's to Launchpad rather than the current bug system.
| validating here as well would mean a redundant leadership check. | ||
| """ | ||
| if self._lazy_data is not None: | ||
| self._check_read() |
There was a problem hiding this comment.
Can a relation go away mid-hook? If not, should this call _validate_read instead?
There was a problem hiding this comment.
Not mid-hook (at least according to my understanding of Juju), but it can already be gone when the hook starts. The first read goes through _load and gets {}; the second hits the cache and comes through here, so if this called _validate_read directly a follower would get {} then a RelationDataAccessError for the same databag in the same hook.
| Dead relations tell no tales: reading a broken relation's databag gives | ||
| `{}` rather than raising, and that has to hold whether or not this unit | ||
| could have read the databag while the relation was alive. Without this, | ||
| validating before the read turns the empty dict `_load` returns for a | ||
| `RelationNotFoundError` into an access error -- and for a follower's own | ||
| app databag, into one that talks about a remote application. |
There was a problem hiding this comment.
This confused me for a while when I read it. But I think I understand -- this is explicitly for the _load path, right?
If I'm right that _validate_cached_read could cleanly call _validate_read instead of _check_read (comment), then I wonder if this whole function would be easier to follow if in-lined into _load.
I'm dreaming of something like:
if self.relation.active:
self._validate_read()
else:
return {}
return self._backend.relation_get(
self.relation.id,
self._entity.name,
self._is_app,
relation_name=self.relation.name,
)Maybe there's a good reason this wouldn't work -- for example if self.relation.active is actually expensive to check.
There was a problem hiding this comment.
It's used from both _load and _validate_cached_read (see the other thread - the cached path needs the dead-relation skip too), so inlining would duplicate the guard.
It's now just if self.relation.active: self._validate_read() after your other suggestion, and I've renamed it to _validate_read_if_active which hopefully makes it less confusing. Returning {} without calling relation-get for an inactive relation would be a separate behaviour change, and I'm not sure we should do that.
| # Always check permissions, and do so before reading the current content, so | ||
| # that a unit that can't write gets an error naming the write, rather than one | ||
| # about the read that change detection happens to require. | ||
| self._validate_write(data) |
There was a problem hiding this comment.
Makes sense, running hyrum before merge should hopefully cover it, and if not then as you say, it was arguably a bug on the user's part before anyway.
Guard the dead-relation skip with a check of relation.active rather than catching the access error, rename the helper to _validate_read_if_active to say what it does, give _validate_read a return type, and tighten the comments in _validate_read and update(). No behaviour change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Say that _load validates uncached reads and point at _validate_cached_read for reads served from the cache, since __getitem__ no longer validates on its own. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Hyrum run done: no regressions from this PR. I compared ops (a22d2ab) against this branch across the full charm list, so the only difference between the two runs is |
james-garner-canonical
left a comment
There was a problem hiding this comment.
Sorry for the delay in getting back to this. Thanks for addressing my feedback and answering my questions. Looks good!
Co-authored-by: James Garner <james.garner@canonical.com>
main's _wrap_hookcmd now takes the hook command's arguments as **trace (the trace-leak fix), so the call to _relation_is_gone now passes trace rather than the kwargs name that no longer exists. The traced arguments still include app, unit and endpoint for relation-get and app for relation-set, which is all it needs. Also drop the _relation_is_gone docstring's claim that in, len() and iteration read a databag without checking leadership, which canonical#2738 fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…anonical#2738) A charm that touches its own application databag from a non-leader unit gets this, with nothing in it pointing at leadership: ``` ops.model.ModelError: ERROR permission denied (unauthorized access) ``` ops already has a much better error for exactly this case (`ops/model.py:2049`): ``` <unit> is not leader and cannot read its own application databag ``` However, the charm never sees it. `RelationDataContent.__getitem__` calls `_validate_read()`, but `_GenericLazyMapping.__contains__`, `__iter__` and `__len__` go straight to `_data` → `_load()` → the hook tool with no validation. `update()`'s change detection uses `key not in self`, so it took the unvalidated path and surfaced Juju's raw error. This applies both with `Relation.save()` and also direct usage of `update()`. This PR makes two changes: We now validate on every read path. `_load()` validates the read, so no uncached read can bypass the check. `__getitem__`, `__contains__`, `__iter__`, `__len__` and `__repr__` validate only when the data is already cached (`_validate_cached_read`), otherwise `_load` does it, and doing both would mean a redundant leadership check. This means that a unit that loses leadership after a read gets the same error from `in`, `len()` and iteration as it does from `bag[key]`. `_validate_read()` is almost always very quick (it's checking a few attributes, except in the case where a fresh leadership check is required). Reads on a broken relation still give `{}`, as before. We now check write permission before reading in `update()`. `_validate_write` ran after the diff loop, so a follower writing application data failed on an incidental read that change detection happens to need, rather than on the write it actually asked for. It now raises `<unit> is not leader and cannot write application data.` This also means that `update()` validates every key and value passed in, not only the ones that turn out to be changes. A bad key or value that would have been a no-op, such as `update({1: ''})` or `del bag[1]`, now raises `RelationDataTypeError` rather than silently doing nothing. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: James Garner <james.garner@canonical.com> (cherry picked from commit ac22e59)
…nch (#2964) This cherry-picks fixes from main that were merged between the last backport round (#2789) and 21 November: * #2738: a non-leader touching its own application databag gets the "is not leader" `RelationDataAccessError` on every access path, rather than a bare `ModelError: permission denied`. * #2780: an `_Abort(0)` from the charm's `__init__` (for example, `load_config(errors='blocked')`) is treated as success in `ops.testing`, as it is in production. * #2787: `Context.trace_data` is no longer empty after the first `Context` with opentelemetry-sdk 1.45. * #2824: ops-tracing sends the correct OTLP span kind for spans that aren't INTERNAL. * #2847 and #2867: a `user-id` or `group-id` of 0 is kept in Pebble services and exec checks. * #2857: the consistency checker accepts tagged Juju versions (like `3.6-beta1`) and action parameters with a list of types. * #2877 and #2876: an error connecting the exec websockets cleans up properly. * #2875: errors reading the Pebble response are wrapped in `ConnectionError`, so `Container.can_connect()` returns `False` rather than raising when Pebble drops the connection. * #2827: OTLP/JSON encoding of bytes and mapping attributes, and of dropped attribute counts. * #2870: exec output is decoded incrementally, so a multi-byte character split across messages no longer raises. * #2872: combining layers in Harness and Scenario keeps the check level, and the original `override`, as Pebble does. * #2871: `pull()` works with paths that have non-ASCII characters or leading or trailing whitespace. * #2855 (partly): `State(opened_ports=[ops.Port(...)])` works, and Scenario ports compare equal to an equal `ops.Port`. * #2917: `get_notices(types=...)` filters correctly in Harness and `ops.testing`. * #2901: `push()` escapes backslashes in the filename. It also includes #2090, which was merged in October 2025 but never backported: an action declared with the shorthand (no params or description, so `null` in `actions.yaml`) no longer crashes the consistency checker. There were some adjustments, which are described in the individual commit messages: * #2780: on this branch, a non-zero `_Abort` is raised as is rather than wrapped in `UncaughtCharmError`, so the new tests expect that. The runtime's `_Abort(0)` handling also covers constructing the charm here, so it now only swallows one once the `Ops` object exists (otherwise a leaked `OPERATOR_DISPATCH` ended in an `AttributeError`). This branch also doesn't have the framework close from #2541 when constructing the charm fails, so `Ops` closes the framework itself after swallowing an `_Abort(0)`. * #2857: `JujuVersion` doesn't accept a bare major version like `'3'`, but the checker on this branch always has (and the tests use them), so I kept accepting those. * #2855: I only ported the `ops.Port` and equality parts. The duplicate-entity checks could start failing existing tests, which seems wrong for a maintenance release. The other `State` fixes in #2855 (comparing unit IDs with `is not`, the shared default `BindAddress`, the `deferred()` error message, and the `get_relation` docstring) aren't included either. `State` only replaced `opened_ports` when the converted list compared unequal, which the new equality defeats, so it now always stores the converted ports. * #2875: before Python 3.10, `socket.timeout` isn't a subclass of `TimeoutError`, so it's checked for as well. Otherwise a timeout waiting for Pebble's response became a plain `ConnectionError` on 3.8 and 3.9, and `wait_change()` stopped retrying it. * #2901: I left out the new `ValueError` for a path containing CR, LF, or NUL. It isn't an `OSError` or a `pebble.Error`, so `Container.push_path()` would stop collecting it and give up on the remaining files. Those paths still get Pebble's `APIError`, as before. `push()` only takes a `str` here, so the real Pebble tests (this one and the #2871 one) pass `str(path)`. * There's an extra commit that skips three of the #2827 tests when opentelemetry-sdk drops bytes, mapping, and mixed-type list values before the encoder sees them. The root lock on this branch has 1.34, which does, so `tox -e coverage-tracing` failed. They still run under `tracing/`. #2738 can turn a charm's passing unit tests red, because Harness and Scenario now raise for something production already did, so the 2.23.x release notes should call it out. Something like: > In Harness and `ops.testing`, a non-leader unit can no longer read its own application databag with `in`, `len()` or iteration, or `update()` it, matching what happens in production ([#2738](#2738)). Unit tests that did this will now raise `RelationDataAccessError`. I left out #2748 (it's built on the hookcmds-based error handling, so would need rewriting), #2851 (`push_path` skipping symlinks is a behaviour change), and #2878 (`CheckInfo.level` changes from `None` to `UNSET`). Fixes merged after 21 November can go in the next round. I've run `tox -e lint`, `static`, `unit`, `py3.8-unit`, `coverage-tracing`, and `pebble` locally, as well as lint, static, and unit in `tracing/`. --------- Co-authored-by: James Garner <james.garner@canonical.com> Co-authored-by: Gangavarapu Vivek <gangavarapu.0104@gmail.com> Co-authored-by: Suyash Bhattarai <133975972+ItsM0rty@users.noreply.github.com> Co-authored-by: Ben Hoyt <ben.hoyt@canonical.com> Co-authored-by: nancy <singhnancy2004@gmail.com> Co-authored-by: Matt Patchava <matt.patchava@canonical.com> Co-authored-by: Indian-boult <64060864+Indian-boult@users.noreply.github.com> Co-authored-by: Dima Tisnek <dima.tisnek@canonical.com>
A charm that touches its own application databag from a non-leader unit gets this, with nothing in it pointing at leadership:
ops already has a much better error for exactly this case (
ops/model.py:2049):However, the charm never sees it.
RelationDataContent.__getitem__calls_validate_read(), but_GenericLazyMapping.__contains__,__iter__and__len__go straight to_data→_load()→ the hook tool with no validation.update()'s change detection useskey not in self, so it took the unvalidated path and surfaced Juju's raw error.This applies both with
Relation.save()and also direct usage ofupdate().This PR makes two changes:
We now validate on every read path.
_load()validates the read, so no uncached read can bypass the check.__getitem__,__contains__,__iter__,__len__and__repr__validate only when the data is already cached (_validate_cached_read), otherwise_loaddoes it, and doing both would mean a redundant leadership check. This means that a unit that loses leadership after a read gets the same error fromin,len()and iteration as it does frombag[key]._validate_read()is almost always very quick (it's checking a few attributes, except in the case where a fresh leadership check is required). Reads on a broken relation still give{}, as before.We now check write permission before reading in
update()._validate_writeran after the diff loop, so a follower writing application data failed on an incidental read that change detection happens to need, rather than on the write it actually asked for. It now raises<unit> is not leader and cannot write application data.This also means that
update()validates every key and value passed in, not only the ones that turn out to be changes. A bad key or value that would have been a no-op, such asupdate({1: ''})ordel bag[1], now raisesRelationDataTypeErrorrather than silently doing nothing.