Repository navigation
fix: a gone relation raises RelationNotFoundError, not "permission denied" - #2748
Conversation
…nied" Juju deliberately reports "permission denied" rather than "relation not found" for a relation that has gone from its state, so that the reply doesn't say whether the relation ever existed. ops only mapped the "not found" wording to RelationNotFoundError, so a charm reading the databags of a relation that the uniter still offers but Juju has forgotten about crashed with a bare ModelError instead of reading them as empty. A follower reading its own application databag gets the same wording from Juju 3.6, and that one is a genuine authorisation failure, so it keeps the original error and is still reported as a security event. Nothing else can be refused on a relation that still exists, so every other "permission denied" on a relation hook command now means the relation is gone. That also means a gone relation no longer logs a CRITICAL security event per databag read per hook. `network-get` words it as "relation 2 not found", which the "relation not found" check missed, so that is matched now too. Verified against Juju 3.6.28 and 4.0.14 on LXD, on the consuming side of a cross-model relation after `juju remove-saas <saas> --force`, as leader and as follower. Fixes canonical#2709 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015fqGiHZe1VeNRRiZBUHeVW
…n failure `_relation_is_gone` returned True for every command that isn't `relation-get`, so a follower whose `relation-set --app` Juju refused was told the relation doesn't exist, and the security event that refusal used to log was dropped. A charm can get there with the relation plainly present: `is_leader` caches for the lease renewal period, and a write from outside an observed event handler isn't checked for leadership at all, so the model-level guard can pass on a unit Juju will refuse. Swallowing a real authorisation failure is the one thing this function must not do, and `_check_for_security_event` already carries "cannot write relation settings" in its list for exactly this refusal. `relation-set --app` now gets the same carve-out as reading, which needs no `unit` comparison: the only app databag a unit can write is its own. The docstring said reading was the only command Juju refuses on a relation that still exists. It also records what the carve-out cannot do: a peer relation's app databag is readable by any unit, so "permission denied" from reading one can only mean the relation is gone - but `relation-get`'s kwargs don't say whether it is a peer relation, so a follower reading a peer app databag still gets canonical#2709's behaviour. The gone-relation parametrise still covers `relation-set --app`, since `is-leader` says true there, with a comment saying so and pointing at the new follower test. That test fails without the fix. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
james-garner-canonical
left a comment
There was a problem hiding this comment.
This is a very good change, but currently I find it quite tricky to follow what values we expect Juju to return for which command, and which combinations of values, commands, args, and other state (names, leadership) map to RelationNotFoundError.
PS: It also looks like we're mapping from any hookcmds.Error -- should that be scoped to a specific subtype? Or is that as narrow as hookcmds gets?
Use the hook command error with cached leadership before and after the call, the remaining lease, and quoted stderr. Keep the original cause. Separate authorization-message detection from security logging and remove the relation access-error classification, which is being handled in canonical#2748. Store a refreshed leadership lease only after a successful query, using the timestamp captured before the query. Verify unknown and expired leadership, failed refreshes and retries, command details, exception types, and subprocess-backed error paths.
There was a problem hiding this comment.
Thanks for the fix.
The logic of the fix looks good to me. I read through the tests, and they covered all cases that I thought this fix addressed.
I agreed with James on the confusion around which cmd + kwargs combination we handle, and will wait for the discussion, hence leaving this review as Comment.
hookcmds.Error |
Reviewers found the DRY prefix check hard to follow: it wasn't visible which stderr wordings Juju actually produces for which command, or which combination of command and kwargs ends up as RelationNotFoundError. _relation_is_gone now takes stderr and owns the whole decision, with the set of relation hook commands listed up front and a branch per case that Juju can refuse while the relation still exists. _wrap_hookcmd just calls it. No behaviour change. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
james-garner-canonical
left a comment
There was a problem hiding this comment.
Thanks, this is way easier to follow. I've left some feedback -- mostly minor, but two substantial things:
- We should be able to correctly convert the error for peer relations too.
- We explain why Juju gives "permission denied" on a relation hook command, but not why/when we do actually get "relation not found".
| Known limitation: a *peer* relation's application databag is readable by | ||
| every unit, so "permission denied" from reading one can only mean the | ||
| relation is gone -- but ``relation-get``'s kwargs don't say whether the | ||
| relation is a peer relation, so a follower reading a peer app databag | ||
| still gets the original error and a security event. That is issue #2709 | ||
| in the one case this function carves out. |
There was a problem hiding this comment.
relation-get's kwargs may not say whether the relation is a peer relation, but Ops knows which relations are peer relations, so we should be able to close this gap.
There was a problem hiding this comment.
I've made a stab at this.
Every unit can read a peer relation's application databag, so "permission denied" from reading one can only mean the relation is gone. The backend couldn't tell a peer read from any other read of the unit's own app databag, so a follower still got a ModelError and a security event. Model now tells the backend which endpoints are peers. Also address the review feedback on _relation_is_gone: explain when Juju says "relation not found" and when it says "permission denied", correct why a follower's read can reach Juju at all (ops only checks leadership in __getitem__, not in `in`, `len()` or iteration), inline the regex, type kwargs as Mapping[str, object], and rename the lowercased stderr local. Fixes canonical#2709 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| # The backend needs the peer relations to tell whether "permission | ||
| # denied" from reading an application databag means the relation is gone. | ||
| self._backend._peer_endpoints = frozenset(self._relations._peers) |
There was a problem hiding this comment.
This is a little odd -- is it the only place where Model sets data on its backend? If the backend needs information from meta to do its job, then it seems like meta should be given to backend by the framework, and then Model reads meta from the backend.
Since Model is a public class, changing its __init__ signature would be risky -- even though meta and backend are typed privately, and we document that it shouldn't be instantiated directly, the Model.__init__ method is arguably still technically public. If Hyrum says it's OK though, maybe we should go this route ...
I'd be fine doing it the current way to mitigate backwards compatibility risk, but I wonder if we should flag that more clearly here, and track it as something to tidy up in a future breaking version. Or if you think we'd never actually change it, I could be convinced that this is actually fine.
| return True | ||
| if 'permission denied' not in stderr: | ||
| return False | ||
| # "permission denied" means the relation is gone, except in the two |
There was a problem hiding this comment.
The explanation below breaking down "permission denied" is great. The bit I asked about last review and still am not clear on from the code is when Juju would report "permission denied" instead of "relation not found" to mean the relation is gone.
I believe there used to be some mention of "forgotten" which made me think maybe it's relation not found initially and then becomes permission denied later?
There was a problem hiding this comment.
It's not a matter of duration - it's which side has lost the relation. If the unit agent no longer has it in its hook context, the hook command rejects the -r value locally with "relation not found". If the agent still has it but the controller doesn't, the call reaches the controller, which on 3.6 maps not-found to ErrPerm in the unit agent. 4.0's domain layer returns "relation not found" for some of those instead, which is why the wordings swap. I've rewritten the docstring to say this, but I wonder if it's too much Juju specific detail to include there.
Model was the only place that wrote to its backend's state. _main owns both the metadata and the backend, so it now tells the backend which endpoints are peers once the metadata is loaded. The backend is created before that, so that logging is set up as early as possible, so this can't be a constructor argument. Model.__init__ is unchanged from main. Also address the remaining review feedback on _relation_is_gone: explain that "relation not found" comes from the unit agent when the relation isn't in its hook context, and "permission denied" from the controller when the agent still has the relation but the controller doesn't, rather than implying it depends on how long the relation has been gone. Use an obvious placeholder ID in the `network-get` example. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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>
Resolve the conflict in ops/model.py by keeping _relation_is_gone and taking upstream's return annotation on _check_for_security_event. Switch the new test_security_event_uses_cached_leadership to config-get: with this branch, a "permission denied" from reading a remote unit's databag means the relation is gone, so it no longer raises ModelError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
james-garner-canonical
left a comment
There was a problem hiding this comment.
Thanks, this answers my question about when Juju tells us what -- I think it's good having that documented in the internal docstring. The refactor to have main pass the peers definition to the model backend also looks great.
<!-- The propose-release workflow fills this in as the description of the version-bump pull request. The markers are how the create-draft-release workflow lifts the title's summary and the notes back out of the description when it creates the draft release, so anything written outside them is for reviewers and goes no further. They are HTML comments, which a reader of the pull request doesn't see, so each pair also gets a visible heading just outside it. --> Prepares the 3.9.0 release from `main`. * `CHANGES.md` has a new entry for 3.9.0. * The version strings are updated across ops, ops-scenario, ops-tracing and the tool-versions table. * [Commits since 3.8.2](3.8.2...main) The GitHub release is titled `3.9.0: ` followed by the summary under "Release title", and its body is the notes under "Release notes". Edit both here: this description is where they are read from. Each is wrapped in hidden markers, which you will see when you edit; keep them. Once this is merged, run [Create the draft release](https://github.com/canonical/operator/actions/workflows/create-draft-release.yaml) with this pull request's number. ## Release title <!-- release-title:start --> ModelError exception note and relation data fixes <!-- release-title:end --> ## Release notes <!-- release-notes:start --> This release makes `ModelError` easier to diagnose, tightens how relation data permissions are enforced, and fixes a set of typing and `ops.testing` issues. There is also a new how-to guide on securing a charm. ## New and improved * **`ModelError` now tells you which hook command failed, and during which event** (#2786). When a call to Juju fails, a traceback notes line now shows what was running, so you no longer have to work it out the long full traceback chain. ```python Traceback (most recent call last): ... ops.model.SecretNotFoundError: db-password Hook command 'secret-get' (label='db-password', refresh=False, peek=False) failed during the 'config-changed' hook. ``` * **A how-to guide for securing a charm** (#2721). Read it if you want [guidance on hardening a charm](https://canonical.com/juju/docs/ops/latest/howto/secure-your-charm/). ## Fixes worth knowing about * **A relation that no longer exists raises `RelationNotFoundError`** (#2748). Before this fix, it raised a `ModelError` with "permission denied" text. * **Tracing errors say which destination rejected the data** (#2714). This helps when you send traces to more than one destination. * **Set `on` in charms and libraries without `# type: ignore`** (#2775). Remove any `type: ignore` comments you added to get past the type checker. ### In `ops.testing` * **If your charm's `__init__` ends with `_Abort(0)` (such as a `load_config()` status set), the test treats it as a success** (#2780). Before this fix, `_Abort(0)` counted as a success only when it came from an event handler. ## Contributors Thank you to @cristiangirlea. <!-- release-notes:end --> --------- Co-authored-by: Prints Charming [bot] <ben.hoyt+prints-charming-bot@canonical.com> Co-authored-by: Tony Meyer <tony.meyer@canonical.com> Co-authored-by: Tony Meyer <tony.meyer@gmail.com>
…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>
Juju deliberately reports "permission denied" rather than "relation not found" for a relation that has gone from its state, so that the reply doesn't say whether the relation ever existed. ops only mapped the "not found" wording, so a charm reading the databags of a relation that the uniter still offers but Juju has forgotten about crashed with a bare
ModelErrorinstead of reading them as empty.network-getwords it as "relation 2 not found", which the "relation not found" check missed, so that is matched now too.Verified against Juju 3.6.28 and 4.0.14 on LXD, on the consuming side of a cross-model relation after
juju remove-saas <saas> --force, as leader and as follower. The wordings differ quite a bit between the two versions (on 4.0 the remote databag reads say "relation not found" andnetwork-getis the one that says "permission denied", and a follower can read its own application databag on a live relation), so the tests are parametrised over all of them.Fixes #2709