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/10/18 15:34:22 UTC
(iggy) 04/23: fix(metadata): make acting-user stamping single-site and fail-closed
This is an automated email from the ASF dual-hosted git repository.
hubcio pushed a commit to branch http-listener
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 6ecebd417a20e7539caa4d53ccf0541ab3b25e3b
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Thu Jul 2 14:41:01 2026 +0200
fix(metadata): make acting-user stamping single-site and fail-closed
The RBAC apply gate trusts PrepareHeader.user_id, but only
submit_request_in_process stamped it. The wire ingresses (on_request,
drain_request_queue_into_prepares) forwarded the wire-supplied value,
and a missing ClientTable session defaulted to 0, which the gate's
root short-circuit treats as allow-all. Both paths failed open.
Move the stamp into prepare_request, the funnel every client-op
prepare passes through on the primary, so no ingress can skip it.
Register and Logout are exempt: Register carries the login identity
itself and neither op is gated. A missing session now rejects with
Unauthenticated instead of defaulting to root. A new test drives the
real prepare_request and asserts the built prepare carries the
ClientTable identity, not the wire value.
---
core/metadata/src/impls/metadata.rs | 280 +++++++++++++++++++++++++++++++-----
1 file changed, 248 insertions(+), 32 deletions(-)
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index 8667818f8..d638c420b 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -1294,7 +1294,7 @@ where
#[allow(clippy::future_not_send)]
pub async fn submit_request_in_process(
&self,
- mut message: Message<RequestHeader>,
+ message: Message<RequestHeader>,
) -> Result<Message<GenericHeader>, MetadataSubmitError> {
let request_header = *message.header();
let client_id = request_header.client;
@@ -1343,33 +1343,9 @@ 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;
- }
-
+ // The acting-user RBAC stamp lives in the shared `prepare_request`
+ // (op-guarded, fail-closed on an unknown session). `request_preflight`
+ // above proved this client's session is live, so it resolves there.
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
@@ -1552,10 +1528,11 @@ where
#[allow(clippy::too_many_lines)]
fn prepare_request(
&self,
- message: Message<RequestHeader>,
+ mut message: Message<RequestHeader>,
) -> Result<Message<PrepareHeader>, iggy_common::IggyError> {
let consensus = self.consensus.as_ref().unwrap();
- let header = *message.header();
+ let operation = message.header().operation;
+ let client_id = message.header().client;
// `TruncatePartition` is server-originated (the owning shard resolves a
// client `DeleteSegments` count to a concrete offset) but replicated AS
// the client's own request, so the commit records the client's request
@@ -1563,10 +1540,38 @@ where
// maps to it, so a client cannot construct one directly -- hence the
// `is_client_allowed` gate excludes it; admit it explicitly. The default
// match arm below projects it through unchanged.
- if !header.operation.is_client_allowed() && header.operation != Operation::TruncatePartition
- {
+ if !operation.is_client_allowed() && operation != Operation::TruncatePartition {
return Err(IggyError::InvalidCommand);
}
+
+ // Stamp the acting user id into the replicated header so the in-apply
+ // RBAC gate (`crate::stm::authz`) resolves the same identity on every
+ // replica, WAL replay included (no session table there). Every client-op
+ // prepare funnels through here, primary-only by construction, so stamping
+ // here -- not in the in-process client path alone -- also covers the
+ // wire-plane ingresses (`on_request` and the request-queue drain). The
+ // wire `user_id` is never trusted: it is overwritten for every gated
+ // client op, and a client whose session is unknown is denied here
+ // (fail-closed), never defaulted to root. `Register` / `Logout` are exempt
+ // (see `resolve_acting_user_id`); server-originated internal ops
+ // (`CompleteConsumerGroupRevocation`, the PAT-cleaner delete) build their
+ // prepare directly, bypassing this path, and keep `user_id` 0 (gate skips).
+ if let Some(acting_user_id) =
+ resolve_acting_user_id(operation, client_id, &self.client_table)?
+ {
+ let request_header = bytemuck::checked::from_bytes_mut::<RequestHeader>(
+ &mut message.as_mut_slice()[..size_of::<RequestHeader>()],
+ );
+ request_header.user_id = acting_user_id;
+ }
+
+ // Must be read AFTER the stamp: the `CreateTopic` / `CreatePartitions`
+ // arms hand this `header` copy to `build_prepare_message`, so it has to
+ // carry the stamped acting user. Reading it before the stamp would ship
+ // those prepares with `user_id` 0 = root, silently bypassing the authz
+ // gate. The default arm projects the mutated buffer directly and is
+ // order-independent.
+ let header = *message.header();
let body = &message.as_slice()[size_of::<RequestHeader>()..header.size as usize];
match header.operation {
@@ -2052,12 +2057,47 @@ const fn eviction_reason_for_invalid(operation: Operation) -> EvictionReason {
}
}
+/// Resolve the acting user id to stamp into a client op's replicated
+/// `RequestHeader`, so the in-apply RBAC gate (`crate::stm::authz`) reads the
+/// same identity on every replica (WAL replay has no session table).
+///
+/// - `Ok(Some(id))`: overwrite the header's `user_id` with the committed
+/// session's user; the wire-supplied value is never trusted.
+/// - `Ok(None)`: leave it untouched. `Register` carries the credential-verified
+/// user from login (a mid-`Register` client has no session yet, so a stamp
+/// would zero it) and `Logout` is not gated -- both keep their builder value.
+/// - `Err(Unauthenticated)`: fail-closed. A client op whose `client_id` has no
+/// session cannot be attributed, so it is denied rather than defaulted to
+/// root (`user_id` 0 is the gate's all-allow short-circuit). Every caller
+/// preflights a live session first (`request_preflight` dispatches only on
+/// `New`), so this guards a future ingress that reaches here without one.
+fn resolve_acting_user_id(
+ operation: Operation,
+ client_id: u128,
+ client_table: &RefCell<ClientTable>,
+) -> Result<Option<u32>, IggyError> {
+ if matches!(operation, Operation::Register | Operation::Logout) {
+ return Ok(None);
+ }
+ client_table
+ .borrow()
+ .get_user_id(client_id)
+ .ok_or(IggyError::Unauthenticated)
+ .map(Some)
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::stm::stream::Streams;
use crate::stm::user::Users;
+ use consensus::LocalPipeline;
+ use iggy_binary_protocol::requests::topics::CreateTopicRequest;
use iggy_common::variadic;
+ use journal::prepare_journal::PrepareJournal;
+ use message_bus::{ClientForwardFn, ConnectionLostFn, JoinHandle, ReplicaForwardFn, SendError};
+ use server_common::MESSAGE_ALIGN;
+ use server_common::iobuf::Frozen;
use std::cell::RefCell;
use std::rc::Rc;
@@ -2153,4 +2193,180 @@ mod tests {
"cleared notifier must stay quiet"
);
}
+
+ /// Minimal committed `Register` reply for `ClientTable::commit_register`,
+ /// which reads only `client` and `commit` (the assigned session).
+ fn register_reply(client: u128, session: u64) -> Message<ReplyHeader> {
+ let header_size = size_of::<ReplyHeader>();
+ let mut reply = Message::<ReplyHeader>::new(header_size);
+ let header = bytemuck::checked::try_from_bytes_mut::<ReplyHeader>(
+ &mut reply.as_mut_slice()[..header_size],
+ )
+ .expect("zeroed bytes are a valid ReplyHeader");
+ *header = ReplyHeader {
+ client,
+ request: 0,
+ commit: session,
+ command: Command2::Reply,
+ operation: Operation::Register,
+ ..Default::default()
+ };
+ reply
+ }
+
+ #[test]
+ fn resolve_acting_user_id_skips_register_and_logout() {
+ // Session-lifecycle ops keep the user id their request builder set
+ // (Register's login identity, Logout's ungated value); the ClientTable
+ // is never consulted, so an empty table still yields `Ok(None)`.
+ let client_table = RefCell::new(ClientTable::new(CLIENTS_TABLE_MAX));
+ for operation in [Operation::Register, Operation::Logout] {
+ assert!(
+ matches!(
+ resolve_acting_user_id(operation, 1, &client_table),
+ Ok(None)
+ ),
+ "{operation:?} must not be stamped"
+ );
+ }
+ }
+
+ #[test]
+ fn resolve_acting_user_id_stamps_from_client_table() {
+ // A gated client op takes the acting user from the committed session,
+ // independent of any wire-supplied header value.
+ const CLIENT: u128 = 1;
+ const SESSION: u64 = 10;
+ const ACTING_USER: u32 = 7;
+ let mut table = ClientTable::new(CLIENTS_TABLE_MAX);
+ table.commit_register(CLIENT, ACTING_USER, register_reply(CLIENT, SESSION), |_| {
+ false
+ });
+ let client_table = RefCell::new(table);
+
+ match resolve_acting_user_id(Operation::CreateStream, CLIENT, &client_table) {
+ Ok(Some(user_id)) => assert_eq!(user_id, ACTING_USER),
+ other => panic!("expected Ok(Some({ACTING_USER})), got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn resolve_acting_user_id_fails_closed_for_unknown_session() {
+ // A gated client op with no committed session is denied, never
+ // defaulted to root (user id 0).
+ let client_table = RefCell::new(ClientTable::new(CLIENTS_TABLE_MAX));
+ match resolve_acting_user_id(Operation::CreateStream, 999, &client_table) {
+ Err(IggyError::Unauthenticated) => {}
+ other => panic!("expected Err(Unauthenticated), got {other:?}"),
+ }
+ }
+
+ /// No-op bus: `prepare_request` builds a prepare without ever sending, so
+ /// every method is an unused stub.
+ #[derive(Debug, Default)]
+ struct NoopBus;
+
+ impl MessageBus for NoopBus {
+ fn track_background(&self, _handle: JoinHandle<()>) {}
+ async fn send_to_client(
+ &self,
+ _client_id: u128,
+ _data: Frozen<MESSAGE_ALIGN>,
+ ) -> Result<(), SendError> {
+ Ok(())
+ }
+ async fn send_to_replica(
+ &self,
+ _replica: u8,
+ _data: Frozen<MESSAGE_ALIGN>,
+ ) -> Result<(), SendError> {
+ Ok(())
+ }
+ fn set_connection_lost_fn(&self, _f: ConnectionLostFn) {}
+ fn set_replica_forward_fn(&self, _f: ReplicaForwardFn) {}
+ fn set_client_forward_fn(&self, _f: ClientForwardFn) {}
+ }
+
+ /// Single-node metadata plane whose `prepare_request` is callable. `J` is
+ /// `PrepareJournal` in name only (the value is `None`) to satisfy the
+ /// impl-block bound; no journal or snapshot is constructed.
+ fn metadata_plane() -> IggyMetadata<VsrConsensus<NoopBus>, PrepareJournal, (), TestMux> {
+ let consensus = VsrConsensus::new(
+ 1,
+ 0,
+ 1,
+ server_common::sharding::METADATA_CONSENSUS_NAMESPACE,
+ NoopBus,
+ LocalPipeline::new(),
+ );
+ consensus.init();
+ IggyMetadata::new(Some(consensus), None, None, TestMux::default(), None)
+ }
+
+ fn create_topic_request(client: u128, wire_user_id: u32) -> Message<RequestHeader> {
+ let body = CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(1),
+ partitions_count: 1,
+ compression_algorithm: 0,
+ message_expiry: 0,
+ max_topic_size: 0,
+ replication_factor: 1,
+ name: WireName::new("t").unwrap(),
+ }
+ .to_bytes();
+ let header_size = size_of::<RequestHeader>();
+ let total = header_size + body.len();
+ let mut message = Message::<RequestHeader>::new(total);
+ {
+ let slice = message.as_mut_slice();
+ slice[header_size..total].copy_from_slice(&body);
+ let header =
+ bytemuck::checked::from_bytes_mut::<RequestHeader>(&mut slice[..header_size]);
+ *header = RequestHeader {
+ command: Command2::Request,
+ operation: Operation::CreateTopic,
+ size: u32::try_from(total).unwrap(),
+ client,
+ session: 1,
+ request: 1,
+ user_id: wire_user_id,
+ namespace: server_common::sharding::METADATA_CONSENSUS_NAMESPACE,
+ ..Default::default()
+ };
+ }
+ message
+ }
+
+ #[test]
+ fn prepare_request_stamps_create_topic_from_client_table_not_wire() {
+ // `CreateTopic` is the projection that reaches `build_prepare_message`
+ // through the post-stamp `header` copy, so the built prepare must carry
+ // the ClientTable identity, not the (bogus) wire value. This pins the
+ // stamp-then-re-read ordering: a hoist would ship `user_id` 0 = root.
+ const CLIENT: u128 = 1;
+ const SESSION: u64 = 10;
+ const ACTING_USER: u32 = 7;
+ const WIRE_USER: u32 = 999;
+ let plane = metadata_plane();
+ plane.client_table.borrow_mut().commit_register(
+ CLIENT,
+ ACTING_USER,
+ register_reply(CLIENT, SESSION),
+ |_| false,
+ );
+
+ let prepare = plane
+ .prepare_request(create_topic_request(CLIENT, WIRE_USER))
+ .expect("CreateTopic is client-allowed");
+ assert_eq!(
+ prepare.header().operation,
+ Operation::CreateTopicWithAssignments,
+ "CreateTopic projects to the enriched form"
+ );
+ assert_eq!(
+ prepare.header().user_id,
+ ACTING_USER,
+ "prepare must carry the ClientTable identity, not the wire value"
+ );
+ }
}