You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by hg...@apache.org on 2026/07/02 22:08:29 UTC
(iggy) 22/43: feat(metadata): enforce RBAC in the metadata apply path
This is an automated email from the ASF dual-hosted git repository.
hubcio pushed a commit to branch http-listener-rebased
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit dc246adea799d8db614c5b2870439959da0c079e
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Thu Jul 2 13:17:26 2026 +0200
feat(metadata): enforce RBAC in the metadata apply path
server-ng authorized nothing on the control plane: any authenticated
user could run every metadata op. The permissioner was live but had no
caller.
Gate every committed metadata op through an authorize step before its
state handler runs, at all three apply sites (primary commit, journal
replay, recovery) so the decision is recomputed identically on every
replica from the acting user id carried in the prepare header. A denied
op commits as a deterministic no-op returning Unauthorized, keeping the
log identical everywhere rather than dropping the entry on one node.
The acting user is stamped from the client table at submit; it can only
be the credential-verified user, never a wire-supplied value. The gate
short-circuits the root user (slab id 0), so root deletion and root
permission changes are now rejected in-apply as legacy does, keeping
that slot permanently root and the short-circuit sound. The simulator
seeds root to match the always-rooted production world.
---
core/consensus/src/impls.rs | 5 +-
core/metadata/src/impls/metadata.rs | 45 +-
core/metadata/src/impls/recovery.rs | 6 +-
core/metadata/src/stm/authz.rs | 758 +++++++++++++++++++++
core/metadata/src/stm/mod.rs | 1 +
core/metadata/src/stm/result.rs | 50 +-
core/metadata/src/stm/stream.rs | 8 +-
core/metadata/src/stm/user.rs | 118 +++-
core/simulator/src/replica.rs | 4 +
core/simulator/src/workload/ops/delete_user.rs | 7 +-
.../src/workload/ops/update_permissions.rs | 2 +
11 files changed, 990 insertions(+), 14 deletions(-)
diff --git a/core/consensus/src/impls.rs b/core/consensus/src/impls.rs
index 6521ecc3c..6b9a9c457 100644
--- a/core/consensus/src/impls.rs
+++ b/core/consensus/src/impls.rs
@@ -2087,8 +2087,9 @@ where
timestamp,
operation: old.operation,
namespace: old.namespace,
- // Inert for non-register ops (they carry 0); on Register it
- // replicates the acting user to every backup.
+ // Copied verbatim: carries the stamped acting user for client
+ // ops (and the authenticated user on Register), so the in-apply
+ // RBAC gate resolves the same identity on every backup.
user_id: old.user_id,
..Default::default()
}
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index b8c50f666..8667818f8 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -16,6 +16,7 @@
// under the License.
use crate::MuxStateMachine;
+use crate::stm::authz::gated_apply;
use crate::stm::consumer_group::CompleteConsumerGroupRevocationRequest;
use crate::stm::snapshot::{FillSnapshot, MetadataSnapshot, Snapshot, SnapshotError};
use crate::stm::stream::{Streams, TruncatePartitionRequest};
@@ -341,8 +342,8 @@ fn require_shard_zero<'a, T>(
slot
}
-/// Late-bound callback invoked after every successful
-/// `mux_stm.update(prepare)` on shard 0's metadata commit path.
+/// Late-bound callback invoked after every committed op on shard 0's metadata
+/// commit path (via `gated_apply`, including a gated no-op).
///
/// Wired by server-ng bootstrap once the metadata bundle has broadcast;
/// receives the committed [`Operation`] so the recipient can filter (the
@@ -799,7 +800,7 @@ where
// Normal op: apply SM, commit_reply. `Err` is decode/corruption
// only; a business rejection commits as a deterministic no-op
// whose `code` rides the reply body, replayed on retry.
- let apply = self.mux_stm.update(prepare).unwrap_or_else(|err| {
+ let apply = gated_apply(&self.mux_stm, prepare).unwrap_or_else(|err| {
panic!(
"on_ack: committed metadata op={} failed to apply: {err}",
prepare_header.op
@@ -1293,7 +1294,7 @@ where
#[allow(clippy::future_not_send)]
pub async fn submit_request_in_process(
&self,
- message: Message<RequestHeader>,
+ mut message: Message<RequestHeader>,
) -> Result<Message<GenericHeader>, MetadataSubmitError> {
let request_header = *message.header();
let client_id = request_header.client;
@@ -1342,6 +1343,33 @@ where
return Err(MetadataSubmitError::PipelineFull);
}
+ // Stamp the acting user id into the request header for the in-apply RBAC
+ // gate, overwriting any wire-supplied value (never trusted). The cluster
+ // resolves session -> user at Register (f1) and the gate must run
+ // identically on every replica, so identity rides the replicated prepare
+ // rather than a per-node session table. `request_preflight` above proved
+ // the session is live, so `get_user_id` is `Some`; the `unwrap_or(0)` is
+ // an unreachable guard, not a root grant (0 is only root's genuine id).
+ //
+ // Kept here rather than hoisted into the shared `prepare_request`:
+ // `Register` and `Logout` funnel through it too, and a mid-`Register`
+ // client has no committed session yet (`get_user_id` is `None`), so a
+ // blanket stamp there would zero `Register`'s f1 user id. The wire
+ // ingresses (`on_request`, `drain_request_queue_into_prepares`) are not
+ // client-reachable today; closing that latent gap needs an op-guarded
+ // stamp, tracked separately.
+ let acting_user_id = self
+ .client_table
+ .borrow()
+ .get_user_id(client_id)
+ .unwrap_or(0);
+ {
+ let header = bytemuck::checked::from_bytes_mut::<RequestHeader>(
+ &mut message.as_mut_slice()[..size_of::<RequestHeader>()],
+ );
+ header.user_id = acting_user_id;
+ }
+
let Ok(prepare) = self.prepare_request(message) else {
// Structurally-invalid request. Return an eviction frame (relayed to
// the socket by the home shard) rather than `Canceled`, which leaves
@@ -1706,7 +1734,7 @@ where
// Normal op: apply SM, commit_reply. `Err` is decode/corruption
// only; a business rejection commits as a deterministic no-op
// whose `code` rides the reply body, replayed on retry.
- let apply = self.mux_stm.update(prepare).unwrap_or_else(|err| {
+ let apply = gated_apply(&self.mux_stm, prepare).unwrap_or_else(|err| {
panic!("commit_journal: committed metadata op={op} failed to apply: {err}");
});
// Post-commit notifier (e.g. partition reconciler
@@ -2001,6 +2029,13 @@ where
timestamp,
operation,
namespace: request.namespace,
+ // Carry the acting user id so the in-apply RBAC gate sees the same
+ // identity on every replica. The default projection copies it (see
+ // `Project::project`); this helper builds prepares for the ops it
+ // rewrites (CreateTopic/CreatePartitions assignment forms,
+ // TruncatePartition), which would otherwise reset it to 0 via
+ // `..Default::default()`.
+ user_id: request.user_id,
..Default::default()
};
diff --git a/core/metadata/src/impls/recovery.rs b/core/metadata/src/impls/recovery.rs
index a32e558f9..4268c1633 100644
--- a/core/metadata/src/impls/recovery.rs
+++ b/core/metadata/src/impls/recovery.rs
@@ -17,6 +17,7 @@
use crate::impls::metadata::IggySnapshot;
use crate::stm::StateMachine;
+use crate::stm::authz::GatedApply;
use crate::stm::snapshot::{MetadataSnapshot, RestoreSnapshot, Snapshot, SnapshotError};
use iggy_binary_protocol::consensus::PrepareHeader;
use iggy_common::IggyError;
@@ -107,6 +108,7 @@ pub struct RecoveredMetadata<M> {
pub async fn recover<M>(data_dir: &Path) -> Result<RecoveredMetadata<M>, RecoveryError>
where
M: StateMachine<Input = Message<PrepareHeader>, Error = IggyError>
+ + GatedApply
+ RestoreSnapshot<MetadataSnapshot>
+ Default,
{
@@ -148,7 +150,9 @@ where
format!("failed to read journal entry for op={}", header.op),
))
})?;
- mux_stm.update(entry)?;
+ // WAL replay must recompute authorization denials identically to the
+ // primary/backup commit paths, so it goes through the same gate.
+ mux_stm.gated_update(entry)?;
last_applied_op = Some(header.op);
}
diff --git a/core/metadata/src/stm/authz.rs b/core/metadata/src/stm/authz.rs
new file mode 100644
index 000000000..35bfdf122
--- /dev/null
+++ b/core/metadata/src/stm/authz.rs
@@ -0,0 +1,758 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! In-apply control-plane authorization for the metadata state machine.
+//!
+//! Every committed client op is gated here before its `StateHandler::apply`
+//! runs. A denial returns an `Unauthorized` [`ApplyReply`] WITHOUT touching
+//! state, so the op commits as a deterministic no-op whose error rides the
+//! cached reply and replays on retry, exactly like a business rejection.
+//!
+//! Replay-determinism invariant: [`authorize`] is a pure function of the
+//! prepare header (`operation` + the acting `user_id`, stamped into the
+//! replicated header at submit time) and the committed permission/stream
+//! state as of the op immediately before this one. That state is applied in
+//! the same order on every replica, so the primary (`on_ack`), each backup
+//! (`commit_journal`), and WAL replay (`recover`) all recompute the identical
+//! decision. This is why identity must ride the header rather than being
+//! resolved from a local session table: a backup has no session for the
+//! acting client.
+
+use crate::MuxStateMachine;
+use crate::impls::metadata::StreamsFrontend;
+use crate::permissioner::Permissioner;
+use crate::stm::StateMachine;
+use crate::stm::consumer_group::{JoinConsumerGroupRequest, LeaveConsumerGroupRequest};
+use crate::stm::result::ApplyReply;
+use crate::stm::stream::{Streams, TruncatePartitionRequest};
+use crate::stm::user::Users;
+use iggy_binary_protocol::requests::consumer_groups::{
+ CreateConsumerGroupRequest, DeleteConsumerGroupRequest,
+};
+use iggy_binary_protocol::requests::partitions::{
+ CreatePartitionsWithAssignmentsRequest, DeletePartitionsRequest,
+};
+use iggy_binary_protocol::requests::streams::{
+ DeleteStreamRequest, PurgeStreamRequest, UpdateStreamRequest,
+};
+use iggy_binary_protocol::requests::topics::{
+ CreateTopicWithAssignmentsRequest, DeleteTopicRequest, PurgeTopicRequest, UpdateTopicRequest,
+};
+use iggy_binary_protocol::requests::users::ChangePasswordRequest;
+use iggy_binary_protocol::{Operation, PrepareHeader, WireDecode, WireIdentifier};
+use iggy_common::{IggyError, variadic};
+use server_common::Message;
+use std::mem::size_of;
+
+/// Gate a committed prepare, then apply it. A denial commits as an
+/// `Unauthorized` no-op (the gate never mutates state); an allow proceeds to
+/// the normal state-machine dispatch. This is the single funnel every
+/// production apply path uses, so no committed op can bypass the RBAC check.
+///
+/// The primary (`on_ack`) and backup (`commit_journal`) paths hold the concrete
+/// mux and call this directly; WAL replay (`recover`) is generic over the state
+/// machine and reaches it through [`GatedApply`].
+///
+/// # Errors
+/// Propagates the underlying [`StateMachine::update`] error (decode / corruption
+/// of a committed body), which is fatal on the commit path.
+pub(crate) fn gated_apply<M>(
+ mux: &M,
+ prepare: Message<PrepareHeader>,
+) -> Result<ApplyReply, IggyError>
+where
+ M: StreamsFrontend
+ + StateMachine<Input = Message<PrepareHeader>, Output = ApplyReply, Error = IggyError>,
+{
+ if let Some(denied) = authorize(&prepare, mux.users(), mux.streams()) {
+ return Ok(denied);
+ }
+ mux.update(prepare)
+}
+
+/// Generic entry point to [`gated_apply`] for the WAL-replay path.
+///
+/// The replay path is generic over the state machine and cannot name the
+/// concrete accessors, so it dispatches through this trait. Implemented only
+/// for the metadata mux (and, in tests, the empty state machine used by the
+/// recovery harness).
+pub trait GatedApply:
+ StateMachine<Input = Message<PrepareHeader>, Output = ApplyReply, Error = IggyError>
+{
+ /// See [`gated_apply`].
+ ///
+ /// # Errors
+ /// Propagates the underlying [`StateMachine::update`] error.
+ fn gated_update(&self, prepare: Message<PrepareHeader>) -> Result<ApplyReply, IggyError>;
+}
+
+impl GatedApply for MuxStateMachine<variadic!(Users, Streams)> {
+ fn gated_update(&self, prepare: Message<PrepareHeader>) -> Result<ApplyReply, IggyError> {
+ gated_apply(self, prepare)
+ }
+}
+
+/// The root user is always the first user created (slab id 0) and holds every
+/// grant. Short-circuited below rather than checked against the permissioner so
+/// the gate is correct even in a cluster that provisions no users (the
+/// deterministic simulator boots none, so its permissioner is empty).
+const ROOT_USER_ID: u32 = 0;
+
+/// Decides whether the acting user may run this committed op.
+///
+/// `Some(reply)` denies with a committed `Unauthorized` no-op; `None` allows
+/// the op to reach its `StateHandler::apply`. Only control-plane client ops are
+/// checked; internal / server-originated ops (which carry `user_id` 0), the
+/// self-scoped personal-access-token ops (no legacy RBAC), the pre-projection
+/// wire forms, and partition-plane ops all pass through.
+///
+/// Object ids are resolved against committed stream state first; a resolution
+/// miss passes through so `apply` produces its own `NotFound`, preserving the
+/// legacy notfound-before-permission ordering.
+#[allow(clippy::too_many_lines)]
+pub(crate) fn authorize(
+ prepare: &Message<PrepareHeader>,
+ users: &Users,
+ streams: &Streams,
+) -> Option<ApplyReply> {
+ let header = prepare.header();
+ let user_id = header.user_id;
+
+ if user_id == ROOT_USER_ID {
+ return None;
+ }
+ let body = &prepare.as_slice()[size_of::<PrepareHeader>()..header.size as usize];
+
+ match header.operation {
+ // Streams. `create_stream` is unscoped; the rest resolve the stream id.
+ Operation::CreateStream => check(users, |perm| perm.create_stream(user_id)),
+ Operation::UpdateStream => {
+ let Ok(request) = UpdateStreamRequest::decode_from(body) else {
+ return None;
+ };
+ stream_scoped(users, streams, &request.stream_id, |perm, sid| {
+ perm.update_stream(user_id, sid)
+ })
+ }
+ Operation::DeleteStream => {
+ let Ok(request) = DeleteStreamRequest::decode_from(body) else {
+ return None;
+ };
+ stream_scoped(users, streams, &request.stream_id, |perm, sid| {
+ perm.delete_stream(user_id, sid)
+ })
+ }
+ Operation::PurgeStream => {
+ let Ok(request) = PurgeStreamRequest::decode_from(body) else {
+ return None;
+ };
+ stream_scoped(users, streams, &request.stream_id, |perm, sid| {
+ perm.purge_stream(user_id, sid)
+ })
+ }
+
+ // Topics. The wire `CreateTopic` is projected to
+ // `CreateTopicWithAssignments` before it reaches apply, so only the
+ // enriched form is gated. `create_topic` is stream-scoped.
+ Operation::CreateTopicWithAssignments => {
+ let Ok(request) = CreateTopicWithAssignmentsRequest::decode_from(body) else {
+ return None;
+ };
+ stream_scoped(users, streams, &request.request.stream_id, |perm, sid| {
+ perm.create_topic(user_id, sid)
+ })
+ }
+ Operation::UpdateTopic => {
+ let Ok(request) = UpdateTopicRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.update_topic(user_id, sid, tid),
+ )
+ }
+ Operation::DeleteTopic => {
+ let Ok(request) = DeleteTopicRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.delete_topic(user_id, sid, tid),
+ )
+ }
+ Operation::PurgeTopic => {
+ let Ok(request) = PurgeTopicRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.purge_topic(user_id, sid, tid),
+ )
+ }
+
+ // Partitions. Wire `CreatePartitions` is projected to the enriched
+ // form; `DeleteSegments` is resolved server-side to `TruncatePartition`
+ // carrying the original client's id.
+ Operation::CreatePartitionsWithAssignments => {
+ let Ok(request) = CreatePartitionsWithAssignmentsRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.request.stream_id,
+ &request.request.topic_id,
+ |perm, sid, tid| perm.create_partitions(user_id, sid, tid),
+ )
+ }
+ Operation::DeletePartitions => {
+ let Ok(request) = DeletePartitionsRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.delete_partitions(user_id, sid, tid),
+ )
+ }
+ Operation::TruncatePartition => {
+ let Ok(request) = TruncatePartitionRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.delete_segments(user_id, sid, tid),
+ )
+ }
+
+ // Consumer groups. Join/Leave carry the enriched request types that add
+ // the VSR client id; Create/Delete use the wire types.
+ Operation::CreateConsumerGroup => {
+ let Ok(request) = CreateConsumerGroupRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.create_consumer_group(user_id, sid, tid),
+ )
+ }
+ Operation::DeleteConsumerGroup => {
+ let Ok(request) = DeleteConsumerGroupRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.delete_consumer_group(user_id, sid, tid),
+ )
+ }
+ Operation::JoinConsumerGroup => {
+ let Ok(request) = JoinConsumerGroupRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.join_consumer_group(user_id, sid, tid),
+ )
+ }
+ Operation::LeaveConsumerGroup => {
+ let Ok(request) = LeaveConsumerGroupRequest::decode_from(body) else {
+ return None;
+ };
+ topic_scoped(
+ users,
+ streams,
+ &request.stream_id,
+ &request.topic_id,
+ |perm, sid, tid| perm.leave_consumer_group(user_id, sid, tid),
+ )
+ }
+
+ // Users. Unscoped `manage_users`, except `ChangePassword` which the
+ // legacy execution layer exempts when the target is the acting user.
+ Operation::CreateUser => check(users, |perm| perm.create_user(user_id)),
+ Operation::DeleteUser => check(users, |perm| perm.delete_user(user_id)),
+ Operation::UpdateUser => check(users, |perm| perm.update_user(user_id)),
+ Operation::UpdatePermissions => check(users, |perm| perm.update_permissions(user_id)),
+ Operation::ChangePassword => {
+ let Ok(request) = ChangePasswordRequest::decode_from(body) else {
+ return None;
+ };
+ match users.read(|inner| inner.resolve_user_id(&request.user_id)) {
+ // Self-service password change: allowed without `manage_users`.
+ Some(target_id) if target_id == user_id as usize => None,
+ Some(_) => check(users, |perm| perm.change_password(user_id)),
+ // Unknown target passes through to apply's `UserNotFound`.
+ None => None,
+ }
+ }
+
+ // Not gated (listed exhaustively so a new op cannot silently skip the
+ // gate): VSR-reserved ops (never reach apply as client ops),
+ // server-originated internal ops (user_id 0), self-scoped PAT ops (no
+ // legacy RBAC), the pre-projection wire forms, and every partition op.
+ Operation::Reserved
+ | Operation::Register
+ | Operation::NonReplicated
+ | Operation::Logout
+ | Operation::RemoveConsumerGroupMember
+ | Operation::CompleteConsumerGroupRevocation
+ | Operation::CreateTopic
+ | Operation::CreatePartitions
+ | Operation::DeleteSegments
+ | Operation::CreatePersonalAccessToken
+ | Operation::DeletePersonalAccessToken
+ | Operation::SendMessages
+ | Operation::StoreConsumerOffset
+ | Operation::DeleteConsumerOffset
+ | Operation::StoreConsumerOffset2
+ | Operation::DeleteConsumerOffset2 => None,
+ }
+}
+
+/// Maps a permissioner rule outcome to a gate decision: any `Err` (always
+/// `Unauthorized`) denies with a committed `Unauthorized` reply.
+fn check(
+ users: &Users,
+ rule: impl FnOnce(&Permissioner) -> Result<(), IggyError>,
+) -> Option<ApplyReply> {
+ match users.read(|inner| rule(&inner.permissioner)) {
+ Ok(()) => None,
+ Err(error) => Some(ApplyReply::err(error.as_code())),
+ }
+}
+
+/// Resolves a stream id, then runs a stream-scoped rule. A resolution miss
+/// passes through (returns `None`) so apply surfaces its own `NotFound`.
+fn stream_scoped(
+ users: &Users,
+ streams: &Streams,
+ stream_id: &WireIdentifier,
+ rule: impl FnOnce(&Permissioner, usize) -> Result<(), IggyError>,
+) -> Option<ApplyReply> {
+ let stream_id = streams.read(|inner| inner.resolve_stream_id(stream_id))?;
+ check(users, |perm| rule(perm, stream_id))
+}
+
+/// Resolves a (stream, topic) pair, then runs a topic-scoped rule. A miss on
+/// either passes through so apply surfaces its own `NotFound`.
+fn topic_scoped(
+ users: &Users,
+ streams: &Streams,
+ stream_id: &WireIdentifier,
+ topic_id: &WireIdentifier,
+ rule: impl FnOnce(&Permissioner, usize, usize) -> Result<(), IggyError>,
+) -> Option<ApplyReply> {
+ let (stream_id, topic_id) = streams.read(|inner| {
+ let stream_id = inner.resolve_stream_id(stream_id)?;
+ let topic_id = inner.resolve_topic_id(stream_id, topic_id)?;
+ Some((stream_id, topic_id))
+ })?;
+ check(users, |perm| rule(perm, stream_id, topic_id))
+}
+
+/// The recovery unit tests exercise WAL-replay mechanics with an empty state
+/// list (`MuxStateMachine<()>`), which has no permission state and so needs no
+/// gate. Production always uses the `variadic!(Users, Streams)` machine above.
+#[cfg(test)]
+impl GatedApply for MuxStateMachine<()> {
+ fn gated_update(&self, prepare: Message<PrepareHeader>) -> Result<ApplyReply, IggyError> {
+ self.update(prepare)
+ }
+}
+
+#[cfg(test)]
+#[allow(clippy::cast_possible_truncation)]
+mod tests {
+ use super::*;
+ use iggy_binary_protocol::primitives::partition_assignment::CreatedPartitionAssignment;
+ use iggy_binary_protocol::primitives::permissions::{
+ WireGlobalPermissions, WirePermissions, WireStreamPermissions,
+ };
+ use iggy_binary_protocol::requests::streams::CreateStreamRequest;
+ use iggy_binary_protocol::requests::topics::CreateTopicRequest;
+ use iggy_binary_protocol::requests::users::CreateUserRequest;
+ use iggy_binary_protocol::{Command2, WireEncode, WireName};
+ use iggy_common::UserStatus;
+ use server_common::iobuf::Owned;
+
+ const HEADER_SIZE: usize = size_of::<PrepareHeader>();
+ /// Root is the first user, so it takes slab id 0; the first user created
+ /// after it is id 1.
+ const ROOT: u32 = 0;
+ const ALICE: u32 = 1;
+
+ fn mux() -> MuxStateMachine<variadic!(Users, Streams)> {
+ let users = Users::default();
+ users.ensure_root_user("iggy", "hash");
+ let streams = Streams::default();
+ MuxStateMachine::new(variadic!(users, streams))
+ }
+
+ fn make_prepare(
+ op: u64,
+ operation: Operation,
+ user_id: u32,
+ body: &[u8],
+ ) -> Message<PrepareHeader> {
+ let total = HEADER_SIZE + body.len();
+ let mut buffer = Owned::<4096>::zeroed(total);
+ {
+ let header = bytemuck::checked::from_bytes_mut::<PrepareHeader>(
+ &mut buffer.as_mut_slice()[..HEADER_SIZE],
+ );
+ header.command = Command2::Prepare;
+ header.operation = operation;
+ header.op = op;
+ header.user_id = user_id;
+ header.size = u32::try_from(total).unwrap();
+ }
+ buffer.as_mut_slice()[HEADER_SIZE..].copy_from_slice(body);
+ Message::try_from(buffer).unwrap()
+ }
+
+ fn no_grants() -> WireGlobalPermissions {
+ WireGlobalPermissions {
+ manage_servers: false,
+ read_servers: false,
+ manage_users: false,
+ read_users: false,
+ manage_streams: false,
+ read_streams: false,
+ manage_topics: false,
+ read_topics: false,
+ poll_messages: false,
+ send_messages: false,
+ }
+ }
+
+ fn create_user_body(
+ name: &str,
+ global: WireGlobalPermissions,
+ streams: Vec<WireStreamPermissions>,
+ ) -> bytes::Bytes {
+ CreateUserRequest {
+ username: WireName::new(name).unwrap(),
+ password: "hash".to_string(),
+ status: UserStatus::Active.as_code(),
+ permissions: Some(WirePermissions { global, streams }),
+ }
+ .to_bytes()
+ }
+
+ fn create_stream_body(name: &str) -> bytes::Bytes {
+ CreateStreamRequest {
+ name: WireName::new(name).unwrap(),
+ }
+ .to_bytes()
+ }
+
+ fn create_topic_body(stream_id: u32, name: &str) -> bytes::Bytes {
+ CreateTopicWithAssignmentsRequest {
+ request: CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(stream_id),
+ partitions_count: 1,
+ compression_algorithm: 0,
+ message_expiry: 0,
+ max_topic_size: 0,
+ replication_factor: 1,
+ name: WireName::new(name).unwrap(),
+ },
+ partitions: vec![CreatedPartitionAssignment {
+ partition_id: 0,
+ consensus_group_id: 1,
+ }],
+ }
+ .to_bytes()
+ }
+
+ fn change_password_body(target: &str) -> bytes::Bytes {
+ ChangePasswordRequest {
+ user_id: WireIdentifier::named(target).unwrap(),
+ current_password: String::new(),
+ new_password: "new-hash".to_string(),
+ }
+ .to_bytes()
+ }
+
+ fn stream_manage_topics(stream_id: u32) -> WireStreamPermissions {
+ WireStreamPermissions {
+ stream_id,
+ manage_stream: false,
+ read_stream: false,
+ manage_topics: true,
+ read_topics: false,
+ poll_messages: false,
+ send_messages: false,
+ topics: Vec::new(),
+ }
+ }
+
+ const UNAUTHORIZED: u32 = 41;
+
+ #[test]
+ fn given_ungranted_user_when_create_stream_should_deny_and_leave_state_unchanged() {
+ let mux = mux();
+ assert_eq!(
+ mux.gated_update(make_prepare(
+ 1,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", no_grants(), Vec::new()),
+ ))
+ .unwrap()
+ .code,
+ 0,
+ "root may create a user"
+ );
+
+ let reply = mux
+ .gated_update(make_prepare(
+ 2,
+ Operation::CreateStream,
+ ALICE,
+ &create_stream_body("s1"),
+ ))
+ .unwrap();
+
+ assert_eq!(reply.code, UNAUTHORIZED);
+ assert_eq!(
+ mux.streams().read(|inner| inner.items.len()),
+ 0,
+ "denied op must not mutate stream state"
+ );
+ }
+
+ #[test]
+ fn given_manage_streams_grant_when_create_stream_should_allow() {
+ let mux = mux();
+ let grants = WireGlobalPermissions {
+ manage_streams: true,
+ ..no_grants()
+ };
+ mux.gated_update(make_prepare(
+ 1,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", grants, Vec::new()),
+ ))
+ .unwrap();
+
+ let reply = mux
+ .gated_update(make_prepare(
+ 2,
+ Operation::CreateStream,
+ ALICE,
+ &create_stream_body("s1"),
+ ))
+ .unwrap();
+
+ assert_eq!(reply.code, 0);
+ assert_eq!(mux.streams().read(|inner| inner.items.len()), 1);
+ }
+
+ #[test]
+ fn given_stream_scoped_topics_grant_when_create_topic_should_allow_only_that_stream() {
+ let mux = mux();
+ // Streams 0 and 1 (StreamsInner slab is separate from the user slab).
+ mux.gated_update(make_prepare(
+ 1,
+ Operation::CreateStream,
+ ROOT,
+ &create_stream_body("s0"),
+ ))
+ .unwrap();
+ mux.gated_update(make_prepare(
+ 2,
+ Operation::CreateStream,
+ ROOT,
+ &create_stream_body("s1"),
+ ))
+ .unwrap();
+ // Alice may manage topics on stream 0 only.
+ mux.gated_update(make_prepare(
+ 3,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", no_grants(), vec![stream_manage_topics(0)]),
+ ))
+ .unwrap();
+
+ let allowed = mux
+ .gated_update(make_prepare(
+ 4,
+ Operation::CreateTopicWithAssignments,
+ ALICE,
+ &create_topic_body(0, "t"),
+ ))
+ .unwrap();
+ assert_eq!(allowed.code, 0, "grant covers stream 0");
+
+ let denied = mux
+ .gated_update(make_prepare(
+ 5,
+ Operation::CreateTopicWithAssignments,
+ ALICE,
+ &create_topic_body(1, "t"),
+ ))
+ .unwrap();
+ assert_eq!(denied.code, UNAUTHORIZED, "grant does not cover stream 1");
+ }
+
+ #[test]
+ fn given_change_password_when_target_is_self_should_allow_else_deny() {
+ let mux = mux();
+ mux.gated_update(make_prepare(
+ 1,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", no_grants(), Vec::new()),
+ ))
+ .unwrap();
+ mux.gated_update(make_prepare(
+ 2,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("bob", no_grants(), Vec::new()),
+ ))
+ .unwrap();
+
+ let own = mux
+ .gated_update(make_prepare(
+ 3,
+ Operation::ChangePassword,
+ ALICE,
+ &change_password_body("alice"),
+ ))
+ .unwrap();
+ assert_eq!(
+ own.code, 0,
+ "self password change is exempt from manage_users"
+ );
+
+ let other = mux
+ .gated_update(make_prepare(
+ 4,
+ Operation::ChangePassword,
+ ALICE,
+ &change_password_body("bob"),
+ ))
+ .unwrap();
+ assert_eq!(
+ other.code, UNAUTHORIZED,
+ "changing another user needs manage_users"
+ );
+ }
+
+ #[test]
+ fn given_internal_revocation_op_when_authorized_should_skip_the_gate() {
+ let mux = mux();
+ let prepare = make_prepare(1, Operation::CompleteConsumerGroupRevocation, ROOT, &[]);
+ assert!(
+ authorize(&prepare, mux.users(), mux.streams()).is_none(),
+ "server-originated revocation must not be gated"
+ );
+ }
+
+ #[test]
+ fn given_non_root_user_when_create_pat_should_skip_the_gate() {
+ let mux = mux();
+ mux.gated_update(make_prepare(
+ 1,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", no_grants(), Vec::new()),
+ ))
+ .unwrap();
+
+ let prepare = make_prepare(2, Operation::CreatePersonalAccessToken, ALICE, &[]);
+ assert!(
+ authorize(&prepare, mux.users(), mux.streams()).is_none(),
+ "PAT ops are self-scoped (parity: no legacy RBAC)"
+ );
+ }
+
+ // The linchpin: a sequence containing a denied op must produce byte-identical
+ // codes and final state whether applied once (primary on_ack) or replayed
+ // fresh (backup commit_journal / recover). Identity rides the header, so no
+ // session table is consulted.
+ #[test]
+ fn given_sequence_with_denial_when_replayed_fresh_should_be_state_identical() {
+ fn sequence() -> Vec<Message<PrepareHeader>> {
+ vec![
+ make_prepare(
+ 1,
+ Operation::CreateUser,
+ ROOT,
+ &create_user_body("alice", no_grants(), Vec::new()),
+ ),
+ make_prepare(
+ 2,
+ Operation::CreateStream,
+ ROOT,
+ &create_stream_body("s-root"),
+ ),
+ // Alice lacks manage_streams: denied on both passes.
+ make_prepare(
+ 3,
+ Operation::CreateStream,
+ ALICE,
+ &create_stream_body("s-alice"),
+ ),
+ ]
+ }
+
+ let primary = mux();
+ let primary_codes: Vec<u32> = sequence()
+ .into_iter()
+ .map(|prepare| primary.gated_update(prepare).unwrap().code)
+ .collect();
+
+ let replay = mux();
+ let replay_codes: Vec<u32> = sequence()
+ .into_iter()
+ .map(|prepare| replay.gated_update(prepare).unwrap().code)
+ .collect();
+
+ assert_eq!(primary_codes, replay_codes, "replay must be deterministic");
+ assert_eq!(primary_codes[2], UNAUTHORIZED, "alice's create is denied");
+ assert_eq!(primary.streams().read(|inner| inner.items.len()), 1);
+ assert_eq!(replay.streams().read(|inner| inner.items.len()), 1);
+ }
+}
diff --git a/core/metadata/src/stm/mod.rs b/core/metadata/src/stm/mod.rs
index f86c2d2e3..5fc0c10d1 100644
--- a/core/metadata/src/stm/mod.rs
+++ b/core/metadata/src/stm/mod.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+pub mod authz;
pub mod consumer_group;
pub mod mux;
pub mod result;
diff --git a/core/metadata/src/stm/result.rs b/core/metadata/src/stm/result.rs
index 7874729d8..9a3eef484 100644
--- a/core/metadata/src/stm/result.rs
+++ b/core/metadata/src/stm/result.rs
@@ -192,9 +192,15 @@ result_enum!(UpdateUserResult {
UserNotFound = 20,
UsernameAlreadyExists = 46,
});
-result_enum!(DeleteUserResult { UserNotFound = 20 });
+result_enum!(DeleteUserResult {
+ UserNotFound = 20,
+ CannotDeleteUser = 48,
+});
result_enum!(ChangePasswordResult { UserNotFound = 20 });
-result_enum!(UpdatePermissionsResult { UserNotFound = 20 });
+result_enum!(UpdatePermissionsResult {
+ UserNotFound = 20,
+ CannotChangePermissions = 49,
+});
// Personal access tokens.
result_enum!(CreatePersonalAccessTokenResult {
@@ -207,6 +213,12 @@ result_enum!(DeletePersonalAccessTokenResult { NotFound = 20 });
result_enum!(CreateConsumerGroupResult { NameAlreadyExists = 5004 });
result_enum!(DeleteConsumerGroupResult { NotFound = 5000 });
+/// `IggyError::Unauthorized`. Any control-plane op can commit as an in-apply
+/// authorization no-op, so this code is valid for every op regardless of its
+/// own result enum. Pinned to the wire discriminant in
+/// [`tests::given_result_discriminants_then_match_iggy_error_codes`].
+const UNAUTHORIZED_CODE: u32 = 41;
+
/// True if `code` is one this op's result enum declares (`Ok = 0` included).
///
/// The state machine only commits codes from the op's own enum, so an
@@ -215,6 +227,11 @@ result_enum!(DeleteConsumerGroupResult { NotFound = 5000 });
/// section (partition plane) return `true`.
#[must_use]
pub const fn result_code_recognized(operation: Operation, code: u32) -> bool {
+ // The in-apply RBAC gate can deny any control-plane op, committing an
+ // `Unauthorized` no-op, so accept it globally rather than per-op enum.
+ if code == UNAUTHORIZED_CODE {
+ return true;
+ }
match operation {
Operation::CreateStream => CreateStreamResult::from_u32(code).is_some(),
Operation::UpdateStream => UpdateStreamResult::from_u32(code).is_some(),
@@ -325,6 +342,20 @@ mod tests {
));
// Partition-plane ops carry no result section, so any code is accepted.
assert!(result_code_recognized(Operation::SendMessages, 12345));
+ // `Unauthorized` commits for any control-plane op via the in-apply gate,
+ // even though no per-op result enum declares it.
+ assert!(result_code_recognized(
+ Operation::CreateStream,
+ UNAUTHORIZED_CODE
+ ));
+ assert!(result_code_recognized(
+ Operation::CreateUser,
+ UNAUTHORIZED_CODE
+ ));
+ assert!(result_code_recognized(
+ Operation::CreateConsumerGroup,
+ UNAUTHORIZED_CODE
+ ));
}
// Pins every result-enum discriminant to the `IggyError` variant its doc
@@ -451,6 +482,18 @@ mod tests {
resource_not_found
);
+ // CannotDeleteUser (48) - root deletion is rejected in-apply.
+ assert_eq!(
+ u32::from(DeleteUserResult::CannotDeleteUser),
+ IggyError::CannotDeleteUser(0).as_code(),
+ );
+
+ // CannotChangePermissions (49) - root permissions are immutable in-apply.
+ assert_eq!(
+ u32::from(UpdatePermissionsResult::CannotChangePermissions),
+ IggyError::CannotChangePermissions(0).as_code(),
+ );
+
// PersonalAccessTokenAlreadyExists (51).
assert_eq!(
u32::from(CreatePersonalAccessTokenResult::AlreadyExists),
@@ -472,5 +515,8 @@ mod tests {
u32::from(DeleteConsumerGroupResult::NotFound),
IggyError::ConsumerGroupIdNotFound(id(), id()).as_code(),
);
+
+ // Unauthorized (41) - the global in-apply RBAC denial code.
+ assert_eq!(UNAUTHORIZED_CODE, IggyError::Unauthorized.as_code());
}
}
diff --git a/core/metadata/src/stm/stream.rs b/core/metadata/src/stm/stream.rs
index 765e643df..41fb0cce6 100644
--- a/core/metadata/src/stm/stream.rs
+++ b/core/metadata/src/stm/stream.rs
@@ -498,7 +498,7 @@ impl StreamsInner {
self.pending_revocations_count = count;
}
- fn resolve_stream_id(&self, identifier: &WireIdentifier) -> Option<usize> {
+ pub(crate) fn resolve_stream_id(&self, identifier: &WireIdentifier) -> Option<usize> {
match identifier {
WireIdentifier::Numeric(id) => {
let id = *id as usize;
@@ -512,7 +512,11 @@ impl StreamsInner {
}
}
- fn resolve_topic_id(&self, stream_id: usize, identifier: &WireIdentifier) -> Option<usize> {
+ pub(crate) fn resolve_topic_id(
+ &self,
+ stream_id: usize,
+ identifier: &WireIdentifier,
+ ) -> Option<usize> {
let stream = self.items.get(stream_id)?;
match identifier {
WireIdentifier::Numeric(id) => {
diff --git a/core/metadata/src/stm/user.rs b/core/metadata/src/stm/user.rs
index 51e51e60c..a13a50c1b 100644
--- a/core/metadata/src/stm/user.rs
+++ b/core/metadata/src/stm/user.rs
@@ -35,6 +35,7 @@ use iggy_binary_protocol::requests::users::{
use iggy_binary_protocol::responses::users::get_user::UserDetailsResponse;
use iggy_binary_protocol::responses::users::user_response::UserResponse;
use iggy_binary_protocol::{WireIdentifier, WireName};
+use iggy_common::defaults::DEFAULT_ROOT_USER_ID;
use iggy_common::{
GlobalPermissions, IggyExpiry, IggyTimestamp, Permissions, PersonalAccessToken,
StreamPermissions, UserId, UserStatus,
@@ -124,7 +125,7 @@ collect_handlers! {
}
impl UsersInner {
- fn resolve_user_id(&self, identifier: &WireIdentifier) -> Option<usize> {
+ pub(crate) fn resolve_user_id(&self, identifier: &WireIdentifier) -> Option<usize> {
match identifier {
WireIdentifier::Numeric(id) => {
let id = *id as usize;
@@ -429,6 +430,15 @@ impl StateHandler for DeleteUserRequest {
return ApplyReply::err(DeleteUserResult::UserNotFound);
};
+ // Root (slab id 0) is undeletable, matching legacy `CannotDeleteUser`.
+ // The rejection is deterministic, so every replica keeps slab id 0 as
+ // the root user and the in-apply RBAC gate's `user_id == 0` root
+ // short-circuit can never be inherited by a recreated user (the slab
+ // reuses freed keys, so a deleted root's slot would be reclaimed).
+ if user_id == DEFAULT_ROOT_USER_ID as usize {
+ return ApplyReply::err(DeleteUserResult::CannotDeleteUser);
+ }
+
if let Some(user) = state.items.get(user_id) {
let username = user.username.clone();
state.items.remove(user_id);
@@ -475,6 +485,14 @@ impl StateHandler for UpdatePermissionsRequest {
return ApplyReply::err(UpdatePermissionsResult::UserNotFound);
};
+ // Root (slab id 0) permissions are immutable, matching legacy
+ // `CannotChangePermissions`. Rejected before any mutation, so the op is a
+ // committed no-op: root keeps its full grants and the permissioner index
+ // is untouched.
+ if user_id == DEFAULT_ROOT_USER_ID as usize {
+ return ApplyReply::err(UpdatePermissionsResult::CannotChangePermissions);
+ }
+
if let Some(user) = state.items.get_mut(user_id) {
user.permissions = self
.permissions
@@ -964,6 +982,98 @@ mod tests {
assert_eq!(apply.code, u32::from(DeleteUserResult::UserNotFound));
}
+ #[test]
+ fn given_root_user_when_apply_delete_user_should_reject_and_keep_root() {
+ // Production seeds root at slab id 0 (`ensure_root_user`), so the first
+ // slab slot is the root user. Deleting it must be rejected in-apply, or
+ // a later `CreateUser` would reclaim slot 0 and inherit the RBAC gate's
+ // `user_id == 0` root short-circuit.
+ let mut users = UsersInner::new();
+ let root_id = create_user_with(&mut users, "iggy", None);
+ assert_eq!(root_id, DEFAULT_ROOT_USER_ID, "root takes slab id 0");
+
+ let delete_root = DeleteUserRequest {
+ user_id: WireIdentifier::numeric(root_id),
+ };
+ let reply = StateHandler::apply(&delete_root, &mut users, IggyTimestamp::now());
+ assert_eq!(reply.code, u32::from(DeleteUserResult::CannotDeleteUser));
+ assert!(
+ users.items.contains(root_id as usize),
+ "root must survive a delete attempt"
+ );
+
+ // A non-root user (slab id 1) stays deletable: the guard is scoped to
+ // root, so there is no over-block regression.
+ let alice_id = create_user_with(&mut users, "alice", None);
+ assert_ne!(alice_id, DEFAULT_ROOT_USER_ID);
+ let delete_alice = DeleteUserRequest {
+ user_id: WireIdentifier::numeric(alice_id),
+ };
+ let reply = StateHandler::apply(&delete_alice, &mut users, IggyTimestamp::now());
+ assert_eq!(reply.code, 0, "non-root deletion still succeeds");
+ assert!(!users.items.contains(alice_id as usize));
+ }
+
+ #[test]
+ fn given_root_user_when_apply_update_permissions_should_reject_and_keep_grants() {
+ // Root occupies slab id 0 (production `ensure_root_user`). Its
+ // permissions must be immutable in-apply, or a delegated manage_users
+ // admin could tamper with root's grants.
+ let mut users = UsersInner::new();
+ let mut root_global = empty_global();
+ root_global.manage_servers = true;
+ root_global.poll_messages = true;
+ let root_id = create_user_with(
+ &mut users,
+ "iggy",
+ Some(WirePermissions {
+ global: root_global,
+ streams: Vec::new(),
+ }),
+ );
+ assert_eq!(root_id, DEFAULT_ROOT_USER_ID, "root takes slab id 0");
+ assert!(users.permissioner.poll_messages(root_id, 1, 1).is_ok());
+
+ // Attempt to strip root's grants: rejected, nothing mutates.
+ let strip = UpdatePermissionsRequest {
+ user_id: WireIdentifier::numeric(root_id),
+ permissions: None,
+ };
+ let reply = StateHandler::apply(&strip, &mut users, IggyTimestamp::now());
+ assert_eq!(
+ reply.code,
+ u32::from(UpdatePermissionsResult::CannotChangePermissions)
+ );
+ assert!(
+ users
+ .items
+ .get(root_id as usize)
+ .and_then(|user| user.permissions.as_ref())
+ .is_some(),
+ "root permissions must survive"
+ );
+ assert!(
+ users.permissioner.poll_messages(root_id, 1, 1).is_ok(),
+ "root gate access unchanged"
+ );
+
+ // A non-root user's permissions can still be updated: no over-block.
+ let alice_id = create_user_with(&mut users, "alice", None);
+ assert_ne!(alice_id, DEFAULT_ROOT_USER_ID);
+ let mut alice_global = empty_global();
+ alice_global.poll_messages = true;
+ let grant = UpdatePermissionsRequest {
+ user_id: WireIdentifier::numeric(alice_id),
+ permissions: Some(WirePermissions {
+ global: alice_global,
+ streams: Vec::new(),
+ }),
+ };
+ let reply = StateHandler::apply(&grant, &mut users, IggyTimestamp::now());
+ assert_eq!(reply.code, 0, "non-root permission update still succeeds");
+ assert!(users.permissioner.poll_messages(alice_id, 1, 1).is_ok());
+ }
+
fn empty_global() -> WireGlobalPermissions {
WireGlobalPermissions {
manage_servers: false,
@@ -1023,6 +1133,9 @@ mod tests {
#[test]
fn given_poll_grant_when_apply_update_permissions_removes_it_should_return_unauthorized() {
let mut users = UsersInner::new();
+ // Occupy slab id 0 with the (immutable) root user so the poller under
+ // test is a non-root user; root permission changes are rejected in-apply.
+ create_user_with(&mut users, "iggy", None);
let mut global = empty_global();
global.poll_messages = true;
let uid = create_user_with(
@@ -1057,6 +1170,9 @@ mod tests {
#[test]
fn given_permissioned_user_when_apply_delete_user_should_clear_all_indexes() {
let mut users = UsersInner::new();
+ // Occupy slab id 0 with the (undeletable) root user so the victim under
+ // test is a non-root user; root deletion is rejected in-apply.
+ create_user_with(&mut users, "iggy", None);
let mut global = empty_global();
global.poll_messages = true;
global.send_messages = true;
diff --git a/core/simulator/src/replica.rs b/core/simulator/src/replica.rs
index 7e44fefee..aea179ac1 100644
--- a/core/simulator/src/replica.rs
+++ b/core/simulator/src/replica.rs
@@ -47,6 +47,10 @@ pub type Replica = shard::IggyShard<
pub fn new_replica(id: u8, name: String, bus: &Arc<SimOutbox>, replica_count: u8) -> Replica {
let users: Users = UsersInner::new().into();
+ // Seed the root user at slab id 0, matching production bootstrap
+ // (`ensure_root_user`). Root is undeletable in-apply, so keeping it in slot
+ // 0 leaves the workload's users at slab id 1+ and out of any delete attempt.
+ users.ensure_root_user("iggy", "hash");
let streams: Streams = StreamsInner::new().into();
let mux = SimMuxStateMachine::new(variadic!(users, streams));
diff --git a/core/simulator/src/workload/ops/delete_user.rs b/core/simulator/src/workload/ops/delete_user.rs
index 225e025d9..964b8eee8 100644
--- a/core/simulator/src/workload/ops/delete_user.rs
+++ b/core/simulator/src/workload/ops/delete_user.rs
@@ -47,6 +47,8 @@ pub fn sample(
Outcome::UserNotFound => Some(Input {
user: shadow.fabricate_absent_name("user"),
}),
+ // Not a targeted outcome (absent from `OUTCOMES`); never sampled.
+ Outcome::CannotDeleteUser => None,
}
}
@@ -70,6 +72,9 @@ pub fn predicted_effect(input: &Input, outcome: Outcome) -> Effect {
Outcome::Ok => Effect::RemoveUser {
name: input.user.clone(),
},
- Outcome::UserNotFound => Effect::None,
+ // `CannotDeleteUser` is never targeted (the workload's users live at
+ // slab id 1+, never root), but effects dispatch on the committed
+ // outcome, so the arm is required: a rejected delete removes nothing.
+ Outcome::UserNotFound | Outcome::CannotDeleteUser => Effect::None,
}
}
diff --git a/core/simulator/src/workload/ops/update_permissions.rs b/core/simulator/src/workload/ops/update_permissions.rs
index e68e43e53..75169a382 100644
--- a/core/simulator/src/workload/ops/update_permissions.rs
+++ b/core/simulator/src/workload/ops/update_permissions.rs
@@ -47,6 +47,8 @@ pub fn sample(
Outcome::UserNotFound => Some(Input {
user: shadow.fabricate_absent_name("user"),
}),
+ // Not a targeted outcome (absent from `OUTCOMES`); never sampled.
+ Outcome::CannotChangePermissions => None,
}
}