diff --git a/README.md b/README.md index c3361af80..25d353cff 100644 --- a/README.md +++ b/README.md @@ -378,8 +378,10 @@ Service::new() ``` HTTP `POST /{command}` is **off by default**. Browser writes use the -GraphQL command proxy. Call `.with_http_command_routes()` only for an -intentional non-GraphQL ingress. +GraphQL command proxy. For an intentional non-GraphQL ingress (a provider +webhook), expose that one command with `.with_http_command(command, edge)`: +its edge authenticates the request and returns what to dispatch. Call +`.with_http_command_routes()` only behind a trusted proxy. ### 08 · Browser replica @@ -1679,6 +1681,31 @@ curl -X POST http://localhost:3000/counter.initialize \ curl http://localhost:3000/health ``` +To expose one command without trusting any header, give it an edge with `Service::with_http_command`. The edge sees the request headers and JSON body (`null` when empty) and returns an `HttpCommandDispatch { command_id, input, session, principal }`, or a `CausalDispatchError` (a 401 for a bad secret). The command runs through the ledger like any other dispatch, with only the session the edge built, and answers `{ payload, receipt }`. No other command path is mounted. Behind a gateway, `Service::command_gateway_routes(binding)` (feature `gateway`) gives every command path to the service binding, so an unexposed one is the service's 404 rather than a UI page: + +```rust,ignore +fn webhook_edge( + headers: &HeaderMap, + body: Value, +) -> Result { + verify_shared_secret(headers)?; + Ok(HttpCommandDispatch { + command_id: delivery_command_id(&body), + input: body, + session: webhook_session(), + principal: VerifiedPrincipal::internal("system:webhook").expect("a subject"), + }) +} + +let service = Service::new() + .named("identity") + .routes(routes) + .with_http_command("webhook.receive", webhook_edge); +gateway_routes.extend(service.command_gateway_routes("service")); +``` + +`microsvc::command_router(service)` is the command paths alone, to compose under your own router and middleware. + The command ID is a client-created UUIDv7: retrying a request with the same ID replays the committed receipt. A command needs an authenticated user (`x-user-id`), and a role its declaration grants. diff --git a/distributed_cli/skills/distributed-graphql/SKILL.md b/distributed_cli/skills/distributed-graphql/SKILL.md index 7889e32db..9b31455a0 100644 --- a/distributed_cli/skills/distributed-graphql/SKILL.md +++ b/distributed_cli/skills/distributed-graphql/SKILL.md @@ -66,9 +66,12 @@ let service = service.try_with_graphql(engine)?; // GET /graphql — GraphiQL IDE when `.graphiql(true)` ``` -`POST /{command}` stays off unless you call `with_http_command_routes()`. -Call that only for an intentional, independently authenticated ingress. -GraphQL mutations do not need it. +`POST /{command}` stays off. For an intentional, independently authenticated +ingress, expose that one command with `with_http_command(command, edge)`: the +edge checks the request and returns the dispatch (command ID, input, session, +principal). `with_http_command_routes()` opens every command to trusted-proxy +headers. Behind a gateway, `command_gateway_routes(binding)` keeps every +command path on the service. GraphQL mutations need none of these. Build the executable `Service` first and pass that exact instance to `GraphqlEngineBuilder::service`. For `Atomic`, pass the repository handle diff --git a/distributed_cli/skills/distributed-usage/SKILL.md b/distributed_cli/skills/distributed-usage/SKILL.md index 075771feb..ce5693cfa 100644 --- a/distributed_cli/skills/distributed-usage/SKILL.md +++ b/distributed_cli/skills/distributed-usage/SKILL.md @@ -171,8 +171,10 @@ command ledger under its command ID, whichever ingress delivers it: projection atomicity; - for a browser-facing GraphQL service, bind that exact `Service` through `GraphqlEngineBuilder::service` and configure public OIDC. HTTP command - routes stay off; browser writes use only the GraphQL command proxy. Call - `.with_http_command_routes()` only for an intentional non-GraphQL ingress; + routes stay off; browser writes use only the GraphQL command proxy. Expose + one command for an intentional non-GraphQL ingress with + `.with_http_command(command, edge)` (the edge authenticates the request); + call `.with_http_command_routes()` only behind a trusted proxy; - generate the strictly typed client with `distributed client`. Use the `distributed-graphql` skill for the complete route, consistency, diff --git a/docs/application-composition.md b/docs/application-composition.md index 28f47ce4c..0dcc70652 100644 --- a/docs/application-composition.md +++ b/docs/application-composition.md @@ -147,7 +147,7 @@ Outbox dispatcher and eventual consumer are **role-selected**, not copy-pasted p | HTTP command routes | Optional / ingress only (e.g. Zitadel) | | OIDC / identity | API-facing processes | -Primary write path for apps remains GraphQL commands. HTTP command routes stay off unless a process calls `with_http_command_routes`. +Primary write path for apps remains GraphQL commands. HTTP command routes stay off: a process exposes one command with `with_http_command(command, edge)` (the edge authenticates the request), or every command with `with_http_command_routes` behind a trusted proxy. `command_gateway_routes` keeps every command path on the service binding of a gateway. --- diff --git a/src/in_memory_repo/repository.rs b/src/in_memory_repo/repository.rs index edcbc223f..3c53ab425 100644 --- a/src/in_memory_repo/repository.rs +++ b/src/in_memory_repo/repository.rs @@ -402,7 +402,7 @@ impl InMemoryRepository { for message in &batch.outbox_messages { if outbox_storage.contains_key(message.id()) { - return Err(RepositoryError::DuplicateOutboxMessageInBatch { + return Err(RepositoryError::DuplicateOutboxMessage { id: message.id().to_string(), } .into()); diff --git a/src/microsvc/causal.rs b/src/microsvc/causal.rs index f39ba43c2..cb8041d12 100644 --- a/src/microsvc/causal.rs +++ b/src/microsvc/causal.rs @@ -326,6 +326,7 @@ pub(crate) struct AggregatePublication { struct WorkspaceState { aggregates: Vec, identities: HashSet, + external_events: Vec, outbox_messages: Vec, read_model_plans: Vec, snapshots: Vec, @@ -458,6 +459,20 @@ where } impl CausalWorkspace<'_, A> { + /// Stage one external fact. Its causation is the ledger's, applied in + /// [`CausalWorkspaceParts::prepare_domain_publications`]. + pub(crate) fn stage_external_event( + &self, + occurrence: crate::DomainEventOccurrence, + ) -> Result<(), CausalWorkspaceError> { + self.state + .lock() + .map_err(|_| CausalWorkspaceError::Poisoned)? + .external_events + .push(occurrence); + Ok(()) + } + pub(crate) fn stage_outbox(&self, message: OutboxMessage) -> Result<(), CausalWorkspaceError> { self.state .lock() @@ -600,6 +615,7 @@ impl CausalWorkspace<'_, A> { .map_err(|_| CausalWorkspaceError::Poisoned)?; Ok(CausalWorkspaceParts { aggregates: state.aggregates, + external_events: state.external_events, outbox_messages: state.outbox_messages, read_model_plans: state.read_model_plans, snapshots: state.snapshots, @@ -618,6 +634,8 @@ impl CausalWorkspace<'_, A> { /// construction of the ledger-fenced commit batch. pub(crate) struct CausalWorkspaceParts { aggregates: Vec, + /// External facts staged by the handler, causation not yet applied. + external_events: Vec, outbox_messages: Vec, read_model_plans: Vec, snapshots: Vec, @@ -697,6 +715,12 @@ impl CausalWorkspaceParts { .push(OutboxMessage::from_domain_event_occurrence(&occurrence)?); } } + for mut occurrence in std::mem::take(&mut self.external_events) { + occurrence.overwrite_causation_id(causation_id); + self.outbox_messages + .push(OutboxMessage::from_domain_event_occurrence(&occurrence)?); + self.domain_event_occurrences.push(occurrence); + } Ok(()) } diff --git a/src/microsvc/cell_host/sql_store.rs b/src/microsvc/cell_host/sql_store.rs index c2ffb9e35..82e614830 100644 --- a/src/microsvc/cell_host/sql_store.rs +++ b/src/microsvc/cell_host/sql_store.rs @@ -165,7 +165,7 @@ impl CellSqlRepository { ) .await?; if !existing.is_empty() { - return Err(RepositoryError::DuplicateOutboxMessageInBatch { + return Err(RepositoryError::DuplicateOutboxMessage { id: message.id().into(), } .into()); diff --git a/src/microsvc/http.rs b/src/microsvc/http.rs index a805e0c86..4273b083b 100644 --- a/src/microsvc/http.rs +++ b/src/microsvc/http.rs @@ -4,10 +4,13 @@ //! //! ## Routes //! -//! - `POST /{command}` — dispatch a typed command when -//! [`Service::with_http_command_routes`] is set. Body = -//! `{ "commandId", "input" }`, request headers → Session. A body without a -//! `commandId` is a 400. +//! - `POST /{command}` for a command exposed with +//! [`Service::with_http_command`]: its edge authenticates the request and +//! says what to dispatch. No other command path is answered. +//! - `POST /{command}` for every command when +//! [`Service::with_http_command_routes`] is set (trusted-proxy ingress). +//! Body = `{ "commandId", "input" }`, request headers → Session. A body +//! without a `commandId` is a 400. //! - `GET /health` — health check returning `{ "ok": true, "commands": [...] }`. //! - `GET /metrics` — Prometheus text metrics (requires the `metrics` feature); //! unauthenticated by design and intended for private scrape networks only. @@ -39,27 +42,49 @@ use std::sync::Arc; +use axum::body::Bytes; use axum::extract::{DefaultBodyLimit, Path, State}; use axum::http::{HeaderMap, StatusCode}; -use axum::response::IntoResponse; -use axum::routing::get; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; use axum::{Json, Router}; use serde_json::{json, Value}; use super::error::HandlerError; -use super::service::Service; +use super::service::{CausalDispatchError, CausalDispatchResult, Service}; use super::session::Session; use super::MAX_HTTP_BODY_BYTES; +use crate::command_dispatch::VerifiedPrincipal; + +/// What a command's HTTP edge ([`Service::with_http_command`]) dispatches +/// for one authenticated request. +#[derive(Debug)] +pub struct HttpCommandDispatch { + /// The ledger command ID. A redelivery with the same ID replays the + /// stored receipt. + pub command_id: String, + /// The command input. + pub input: Value, + /// The session the command runs with. Request headers reach the command + /// only through what the edge puts here. + pub session: Session, + /// The principal the edge verified. + pub principal: VerifiedPrincipal, +} + +/// A command's HTTP edge: request headers and JSON body in, dispatch out. +pub(crate) type HttpCommandEdge = Arc< + dyn Fn(&HeaderMap, Value) -> Result + Send + Sync, +>; /// Build an axum `Router` that dispatches commands via the given service. /// -/// Does not mount `POST /{command}` unless [`Service::with_http_command_routes`] -/// was called. Health, metrics, and GraphQL stay available either way. +/// Mounts [`command_router`], `GET /health`, metrics, and GraphQL when the +/// service has an engine. pub fn router(service: Arc) -> Router { - let mut router = Router::new().route("/health", get(health_handler)); - if service.http_command_routes_enabled() { - router = router.route("/{command}", axum::routing::post(command_handler)); - } + // Only metrics and GraphQL add routes after this. + #[cfg_attr(not(any(feature = "metrics", feature = "graphql")), allow(unused_mut))] + let mut router = command_router(Arc::clone(&service)).route("/health", get(health_handler)); #[cfg(feature = "metrics")] { router = router.route("/metrics", get(metrics_handler)); @@ -86,11 +111,78 @@ pub fn router(service: Arc) -> Router { router // Pin the body limit explicitly rather than relying on axum's default; - // the command handler buffers the JSON body into memory. + // the command handlers buffer the JSON body into memory. .layer(DefaultBodyLimit::max(MAX_HTTP_BODY_BYTES)) .with_state(service) } +/// The command paths of `service`, and nothing else: `POST /{command}` for +/// each command exposed with [`Service::with_http_command`], and for every +/// command when [`Service::with_http_command_routes`] is set. A command path +/// it does not expose is not mounted, so it is a 404. +/// +/// [`router`] includes it; mount it alone to compose the command paths into +/// another router (with that router's own health route or middleware). It +/// needs its state, so finish it with `.with_state(service)` there, or call +/// [`router`]. +/// +/// # Panics +/// When an edge names a command the service does not register. +pub fn command_router(service: Arc) -> Router> { + let mut router = Router::new(); + if service.http_command_routes_enabled() { + router = router.route("/{command}", post(command_handler)); + } + let registered = service.command_names(); + for (command, edge) in service.http_commands() { + assert!( + registered.contains(&command), + "HTTP edge for `{command}`, which the service does not register" + ); + let command = command.to_string(); + let edge = Arc::clone(edge); + router = router.route( + &format!("/{command}"), + post( + move |State(service): State>, headers: HeaderMap, body: Bytes| { + let command = command.clone(); + let edge = Arc::clone(&edge); + async move { + let result = match request_json(&body) { + Ok(body) => match edge(&headers, body) { + Ok(dispatch) => { + service + .dispatch_causal_with_receipt( + &command, + &dispatch.command_id, + dispatch.input, + dispatch.session, + dispatch.principal, + ) + .await + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + }; + command_response(&command, result) + } + }, + ), + ); + } + router +} + +/// The JSON of a request body; `null` when it is empty. +fn request_json(body: &[u8]) -> Result { + if body.iter().all(u8::is_ascii_whitespace) { + return Ok(Value::Null); + } + serde_json::from_slice(body) + .map_err(|_| CausalDispatchError::BadRequest("request body is not JSON".into())) +} + /// Serve the service over HTTP at the given address (e.g. `"0.0.0.0:3000"`). pub async fn serve(service: Arc, addr: &str) -> Result<(), std::io::Error> { let app = router(service); @@ -147,21 +239,30 @@ async fn command_handler( .into_response(); } }; - match super::wait_path::dispatch_wait_path( + let result = super::wait_path::dispatch_wait_path( service.as_ref(), &command, &command_id, input, session, ) - .await - { + .await; + command_response(&command, result) +} + +/// The HTTP answer of one dispatched command: the wait-path response, or its +/// error with the error's status. +fn command_response( + command: &str, + result: Result, +) -> Response { + match result { Ok(result) => ( StatusCode::OK, Json(super::wait_path::wait_path_response(&result)), ) .into_response(), - Err(super::CausalDispatchError::Handler(HandlerError::ApplicationReloading)) => { + Err(CausalDispatchError::Handler(HandlerError::ApplicationReloading)) => { reloading_response() } Err(err) => { @@ -178,7 +279,7 @@ async fn command_handler( /// The response to a command refused by the service's /// [`LifecycleGate`](super::LifecycleGate). -fn reloading_response() -> axum::response::Response { +fn reloading_response() -> Response { ( StatusCode::SERVICE_UNAVAILABLE, Json(json!({ diff --git a/src/microsvc/mod.rs b/src/microsvc/mod.rs index d0c0d34ac..f060592c9 100644 --- a/src/microsvc/mod.rs +++ b/src/microsvc/mod.rs @@ -154,7 +154,7 @@ mod http; #[allow(unused_imports)] pub(crate) use http::session_from_headers; #[cfg(feature = "http")] -pub use http::{router, serve}; +pub use http::{command_router, router, serve, HttpCommandDispatch}; // Knative / CloudEvents HTTP ingress (Service-coupled; the bus keeps only the // produce/manifest helpers). diff --git a/src/microsvc/service/handlers.rs b/src/microsvc/service/handlers.rs index 8b2451f74..77579ebd0 100644 --- a/src/microsvc/service/handlers.rs +++ b/src/microsvc/service/handlers.rs @@ -176,6 +176,7 @@ pub struct CausalCommitBuilder< context: &'context CausalCommandContext<'route, A>, publish_captured_events: bool, explicit_events: Vec, + external_events: Vec, outbox_messages: Vec, read_model_plans: Vec, error: Option, @@ -191,6 +192,7 @@ impl<'context, 'route, A> context, publish_captured_events: false, explicit_events: Vec::new(), + external_events: Vec::new(), outbox_messages: Vec::new(), read_model_plans: Vec::new(), error: None, @@ -216,6 +218,40 @@ impl<'context, 'route, A, Publication, Projection> context: self.context, publish_captured_events: self.publish_captured_events, explicit_events: self.explicit_events, + external_events: self.external_events, + outbox_messages: self.outbox_messages, + read_model_plans: self.read_model_plans, + error: self.error, + projection: self.projection, + _publication: PhantomData, + } + } + + /// Publish one typed fact from an external source: a provider webhook, a + /// reconciliation, anything that is not an aggregate transition. + /// + /// The fact becomes a [`DomainEventOccurrence`](crate::DomainEventOccurrence) + /// whose identity is `source` alone, so the same source position published + /// twice is one outbox message id (the second commit fails with + /// [`RepositoryError::DuplicateOutboxMessage`](crate::RepositoryError::DuplicateOutboxMessage)). + /// It commits with the command's ledger receipt and carries its causation, + /// so a `projection!` over `E` projects it like an aggregate's event. + pub fn publish_external( + mut self, + source: crate::ExternalEventSource, + event: E, + ) -> CausalCommitBuilder<'context, 'route, A, WithPublication, Projection> { + if self.error.is_none() { + match self.context.capture_external(source, &event) { + Ok(occurrence) => self.external_events.push(occurrence), + Err(error) => self.error = Some(HandlerError::Other(Box::new(error))), + } + } + CausalCommitBuilder { + context: self.context, + publish_captured_events: self.publish_captured_events, + explicit_events: self.explicit_events, + external_events: self.external_events, outbox_messages: self.outbox_messages, read_model_plans: self.read_model_plans, error: self.error, @@ -241,6 +277,12 @@ impl<'context, 'route, A, Publication, Projection> if let Some(error) = self.error.take() { return Err(error); } + for occurrence in self.external_events { + self.context + .workspace + .stage_external_event(occurrence) + .map_err(workspace_handler_error)?; + } for message in self.outbox_messages { self.context .workspace @@ -293,6 +335,7 @@ where context: self.context, publish_captured_events: true, explicit_events: self.explicit_events, + external_events: self.external_events, outbox_messages: self.outbox_messages, read_model_plans: self.read_model_plans, error: self.error, @@ -321,6 +364,7 @@ where context: self.context, publish_captured_events: self.publish_captured_events, explicit_events: self.explicit_events, + external_events: self.external_events, outbox_messages: self.outbox_messages, read_model_plans: self.read_model_plans, error: self.error, @@ -344,6 +388,7 @@ where context: self.context, publish_captured_events: self.publish_captured_events, explicit_events: self.explicit_events, + external_events: self.external_events, outbox_messages: self.outbox_messages, read_model_plans: self.read_model_plans, error: self.error, @@ -531,6 +576,39 @@ impl<'a, A> CausalCommandContext<'a, A> { CausalCommitBuilder::empty(self).outbox(message) } + /// Start a unit of work that publishes one typed fact from an external + /// source. See [`CausalCommitBuilder::publish_external`]. + pub fn publish_external( + &self, + source: crate::ExternalEventSource, + event: E, + ) -> CausalCommitBuilder<'_, 'a, A, WithPublication, NoDirectProjection> { + CausalCommitBuilder::empty(self).publish_external(source, event) + } + + /// Capture `event` from `source` with this command's correlation and + /// trace context. Causation is the ledger's, applied when it commits. + fn capture_external( + &self, + source: crate::ExternalEventSource, + event: &E, + ) -> Result { + let mut metadata = std::collections::HashMap::new(); + self.trace_context().inject_map(&mut metadata); + if let Some(correlation_id) = self.correlation_id() { + metadata.insert( + crate::trace_context::CORRELATION_ID.to_string(), + correlation_id.to_string(), + ); + } + crate::DomainEventOccurrence::capture_external( + source, + crate::time::now(), + metadata.into_iter().collect(), + event, + ) + } + /// The host clock when this command was dispatched: the Durable Object /// clock on celld, the store clock on the reference host and the /// in-memory repository (e.g. a `ManualClock`), the database clock on diff --git a/src/microsvc/service/runtime.rs b/src/microsvc/service/runtime.rs index 313710a59..27aff3905 100644 --- a/src/microsvc/service/runtime.rs +++ b/src/microsvc/service/runtime.rs @@ -72,6 +72,10 @@ pub struct Service { /// When true, HTTP mounts `POST /{command}`. Off by default — GraphQL, /// health, and in-process `dispatch` stay available without this. http_command_routes: bool, + /// Commands exposed one at a time at `POST /{command}`, each through + /// its own HTTP edge. + #[cfg(feature = "http")] + http_commands: BTreeMap, #[cfg(feature = "graphql")] graphql: Option>, /// Started by `with_bus`; stops when the service is dropped. @@ -94,6 +98,8 @@ impl Service { registered_command_mounts: Vec::new(), lifecycle: LifecycleGate::always_open(), http_command_routes: false, + #[cfg(feature = "http")] + http_commands: BTreeMap::new(), #[cfg(feature = "graphql")] graphql: None, #[cfg(feature = "runtime-tokio")] @@ -141,6 +147,74 @@ impl Service { self.http_command_routes } + /// Expose one command at `POST /{command}` through `edge`. + /// + /// The edge authenticates the request from its headers and JSON body + /// (`null` when the body is empty) and returns what to dispatch: the + /// command ID, the input, and the session and principal the command runs + /// as. Only that command runs, through the same ledgered path as every + /// other dispatch, and no request header reaches it unless the edge puts + /// it in the returned session. The answer is the wait-path response + /// (`{ "payload", "receipt" }`, or `{ "code", "error" }` with its status). + /// + /// Use it for an ingress that cannot speak the GraphQL edge, such as a + /// provider webhook signed with a shared secret. Every other command path + /// stays closed; route all of them to the service with + /// [`command_gateway_routes`](Self::command_gateway_routes) so none falls + /// through to a UI. + /// + /// # Panics + /// When `command` already has an edge. + #[cfg(feature = "http")] + pub fn with_http_command(mut self, command: impl Into, edge: F) -> Self + where + F: Fn( + &axum::http::HeaderMap, + Value, + ) -> Result + + Send + + Sync + + 'static, + { + let command = command.into(); + assert!( + !self.http_commands.contains_key(&command), + "command `{command}` already has an HTTP edge" + ); + self.http_commands.insert(command, Arc::new(edge)); + self + } + + /// The commands [`with_http_command`](Self::with_http_command) exposes, + /// with their edges. + #[cfg(feature = "http")] + pub(crate) fn http_commands( + &self, + ) -> impl Iterator { + self.http_commands + .iter() + .map(|(command, edge)| (command.as_str(), edge)) + } + + /// Gateway routes that give `binding` (the binding serving + /// [`router`](crate::microsvc::router)) every command path, `/{command}` + /// exactly, so none falls through to a UI or another prefix owner. The + /// service answers only the commands it exposes; every other command path + /// is a 404 there. + #[cfg(feature = "gateway")] + pub fn command_gateway_routes(&self, binding: &str) -> Vec { + self.command_names() + .into_iter() + .map(|command| { + crate::gateway::Route::new( + format!("command:{command}"), + crate::gateway::RoutePath::exact(format!("/{command}")), + binding, + ) + }) + .collect() + } + /// Configure the durable command attempt lease and replay retention. /// /// The defaults are 30 seconds and 30 days. Retention must remain longer diff --git a/src/repository/error.rs b/src/repository/error.rs index 7cd0a9671..6fde48fc6 100644 --- a/src/repository/error.rs +++ b/src/repository/error.rs @@ -22,7 +22,11 @@ pub enum RepositoryError { DuplicateStreamInBatch { id: String, }, - DuplicateOutboxMessageInBatch { + /// An outbox message id is repeated within the batch, or was already + /// committed. The whole batch rolls back. Message ids are the publication + /// identity, so a producer that derives them from its input (a command id, + /// a source position) can treat this as "already published". + DuplicateOutboxMessage { id: String, }, /// A consumer inbox receipt `(consumer, message_id)` was already recorded. @@ -135,7 +139,7 @@ impl RepositoryError { } RepositoryError::LockPoisoned(_) | RepositoryError::DuplicateStreamInBatch { .. } - | RepositoryError::DuplicateOutboxMessageInBatch { .. } + | RepositoryError::DuplicateOutboxMessage { .. } | RepositoryError::DuplicateInboxReceipt { .. } | RepositoryError::InvalidInboxReceipt { .. } | RepositoryError::CausalWriteRequired { .. } @@ -171,8 +175,8 @@ impl fmt::Display for RepositoryError { RepositoryError::DuplicateStreamInBatch { id } => { write!(f, "duplicate stream id in commit batch: {}", id) } - RepositoryError::DuplicateOutboxMessageInBatch { id } => { - write!(f, "duplicate outbox message id in commit batch: {}", id) + RepositoryError::DuplicateOutboxMessage { id } => { + write!(f, "duplicate outbox message id: {}", id) } RepositoryError::DuplicateInboxReceipt { consumer, diff --git a/src/repository/validation.rs b/src/repository/validation.rs index ac78f39c9..8e9a721f0 100644 --- a/src/repository/validation.rs +++ b/src/repository/validation.rs @@ -113,7 +113,7 @@ fn reject_duplicate_outbox_messages(messages: &[OutboxMessage]) -> Result<(), Re ))); } if !seen.insert(id.to_string()) { - return Err(RepositoryError::DuplicateOutboxMessageInBatch { id: id.into() }); + return Err(RepositoryError::DuplicateOutboxMessage { id: id.into() }); } } Ok(()) diff --git a/src/sqlx_repo/repo/outbox.rs b/src/sqlx_repo/repo/outbox.rs index 95c73b964..69ef76aba 100644 --- a/src/sqlx_repo/repo/outbox.rs +++ b/src/sqlx_repo/repo/outbox.rs @@ -208,7 +208,7 @@ where .and_then(|source| source.downcast_ref::()) .is_some_and(DB::is_unique_violation) { - return Err(RepositoryError::DuplicateOutboxMessageInBatch { + return Err(RepositoryError::DuplicateOutboxMessage { id: insert.first_id.to_string(), }); } diff --git a/tests/common/src/repository/outbox.rs b/tests/common/src/repository/outbox.rs index 1d6fad8b2..ca314263f 100644 --- a/tests/common/src/repository/outbox.rs +++ b/tests/common/src/repository/outbox.rs @@ -120,7 +120,7 @@ where assert!(matches!( err, - RepositoryError::DuplicateOutboxMessageInBatch { .. } + RepositoryError::DuplicateOutboxMessage { .. } )); assert!(repo .get_stream(&rollback_identity) diff --git a/tests/core/aggregate_less_commands/mod.rs b/tests/core/aggregate_less_commands/mod.rs index 54e81c2f8..47b7f178f 100644 --- a/tests/core/aggregate_less_commands/mod.rs +++ b/tests/core/aggregate_less_commands/mod.rs @@ -8,7 +8,9 @@ //! - a second dispatch of one command id replays and stages nothing more; //! - a refusal is recorded and replayed, with nothing staged; //! - a commit that fails records no receipt; -//! - a command that stages nothing succeeds. +//! - a command that stages nothing succeeds; +//! - an external fact (`publish_external`) is published as a domain-event +//! occurrence, identified by its source and caused by the command. //! //! The scenarios run on the in-memory repository and, with `sqlite`, on a //! SQLite file. @@ -22,11 +24,14 @@ use serde_json::json; use distributed::command::{typed_command, PreparedCommand, Succeeded}; use distributed::command_dispatch::{deterministic_command_id, VerifiedPrincipal}; use distributed::microsvc::{ - CausalCommandContext, CausalDispatchError, HandlerError, HasOutboxStore, Routes, Service, - Session, ROLE_KEY, USER_ID_KEY, + CausalCommandContext, CausalDispatchError, CausalDispatchResult, HandlerError, HasOutboxStore, + Routes, Service, Session, ROLE_KEY, USER_ID_KEY, }; use distributed::read_model::ReadModelWritePlanBuilder; -use distributed::{OutboxMessage, OutboxStore, ReadModel, ReadModelWorkspaceExt, RowKey, RowValue}; +use distributed::{ + ExternalEventSource, OutboxMessage, OutboxStore, ReadModel, ReadModelWorkspaceExt, RowKey, + RowValue, +}; const RECEIVE: &str = "webhook.receive"; const SUBJECT: &str = "system:webhook"; @@ -36,11 +41,29 @@ const ROLE: &str = "webhook"; struct ReceiveInput { /// The id of the outbox message the handler stages. delivery: String, - /// `publish`, `record` (also upserts a read-model row), `nothing` or - /// `reject`. + /// `publish`, `record` (also upserts a read-model row), `external` + /// (publishes [`WebhookReceived`] instead of a raw message), `nothing` + /// or `reject`. mode: String, } +/// The external fact the `external` mode publishes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, distributed::DomainEvent)] +#[domain_event(name = "webhook.received", version = 1)] +struct WebhookReceived { + delivery: String, +} + +/// Where the `external` mode's fact comes from: the provider's delivery. +fn webhook_source(delivery: &str) -> ExternalEventSource { + ExternalEventSource { + producer: RECEIVE.into(), + stream: delivery.into(), + position: 1, + key: "delivery".into(), + } +} + #[derive(Debug, Serialize, distributed::CommandOutput)] struct ReceivePayload { published: bool, @@ -92,6 +115,15 @@ async fn receive( }; match input.mode.as_str() { "reject" => Err(HandlerError::Rejected("not a delivery we accept".into())), + "external" => ctx + .publish_external( + webhook_source(&input.delivery), + WebhookReceived { + delivery: input.delivery.clone(), + }, + ) + .commit()? + .succeeded(payload(true)), "nothing" => PreparedCommand::prepare(payload(false)) .map_err(|error| HandlerError::Other(Box::new(error))), "record" => { @@ -137,11 +169,22 @@ async fn dispatch( delivery: &str, mode: &str, ) -> Result { + dispatch_with_receipt(service, command_id, delivery, mode) + .await + .map(|result| result.payload().clone()) +} + +async fn dispatch_with_receipt( + service: &Service, + command_id: &str, + delivery: &str, + mode: &str, +) -> Result { let mut session = Session::new(); session.set(USER_ID_KEY, SUBJECT); session.set(ROLE_KEY, ROLE); service - .dispatch_causal( + .dispatch_causal_with_receipt( RECEIVE, command_id, json!({ "delivery": delivery, "mode": mode }), @@ -245,6 +288,59 @@ macro_rules! scenarios { assert_eq!(staged(&repo.outbox_store(), delivery).await, 0); } + #[tokio::test] + async fn an_external_fact_is_an_occurrence_of_its_source_caused_by_the_command() { + let db = $fresh.await; + let repo: $repo_ty = db.repo().await; + let service = service(repo.clone()); + let delivery = concat!($backend, "-external"); + let id = command_id(delivery); + + let result = dispatch_with_receipt(&service, &id, delivery, "external") + .await + .unwrap(); + let again = dispatch_with_receipt(&service, &id, delivery, "external") + .await + .unwrap(); + assert_eq!(again.causation_id(), result.causation_id()); + assert_eq!(runs(delivery), 1); + + let published: Vec<_> = repo + .outbox_store() + .pending(usize::MAX) + .await + .unwrap() + .into_iter() + .filter_map(|message| { + let occurrence = message.domain_event_occurrence().ok()?; + (occurrence.external_source() == Some(&webhook_source(delivery))) + .then_some((message, occurrence)) + }) + .collect(); + assert_eq!(published.len(), 1, "one occurrence per source"); + let (message, occurrence) = &published[0]; + assert_eq!(message.id(), occurrence.id()); + assert_eq!(message.event_type, "webhook.received"); + assert_eq!(occurrence.causation_id(), Some(result.causation_id())); + assert_eq!( + occurrence.decode_body::().unwrap(), + WebhookReceived { + delivery: delivery.into() + } + ); + + // Another command publishing the same source fact is the typed + // duplicate: its transaction fails whole, with no receipt. + let other = command_id(concat!($backend, "-external-again")); + let error = dispatch(&service, &other, delivery, "external") + .await + .unwrap_err(); + assert!( + matches!(error, CausalDispatchError::Internal(_)), + "{error:?}" + ); + } + #[tokio::test] async fn a_command_that_stages_nothing_succeeds() { let db = $fresh.await; diff --git a/tests/e2e-celld/crates/graphql-service/src/http.rs b/tests/e2e-celld/crates/graphql-service/src/http.rs index 9d68fec4f..1db8ec663 100644 --- a/tests/e2e-celld/crates/graphql-service/src/http.rs +++ b/tests/e2e-celld/crates/graphql-service/src/http.rs @@ -4,7 +4,6 @@ //! shared secret or process-local, not a user Bearer. User writes stay on //! `/graphql`. -use std::collections::HashMap; use std::sync::Arc; use axum::extract::{Request, State}; @@ -18,37 +17,8 @@ use distributed::cell_host::{InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER}; use distributed::command_dispatch::SharedCommandHost; use distributed::gateway::{native::*, *}; use distributed::graphql::identity::OidcGatewayProvider; -use distributed::microsvc::{CausalDispatchError, Service, Session}; -use e2e_celld_identity::handlers::ingestors::{zitadel, zitadel_scrape}; -use serde_json::{json, Value}; - -/// The request's headers, for the ingestor's authenticity check only: they -/// are never the session a command runs with. -fn session_from_headers(headers: &HeaderMap) -> Session { - let mut vars = HashMap::new(); - for (name, value) in headers.iter() { - if let Ok(v) = value.to_str() { - vars.insert(name.as_str().to_string(), v.to_string()); - } - } - Session::from_map(vars) -} - -/// The HTTP answer of a ledgered command. -fn command_response(command: &str, result: Result) -> Response { - match result { - Ok(value) => (StatusCode::OK, Json(value)).into_response(), - Err(error) => { - let status = StatusCode::from_u16(error.status_code()) - .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); - if status.is_server_error() { - eprintln!("command `{command}` failed: {error}"); - } - let body = json!({ "code": error.code(), "error": error.client_message() }); - (status, Json(body)).into_response() - } - } -} +use distributed::microsvc::{self, Service}; +use serde_json::json; async fn require_internal( State(secret): State, @@ -88,8 +58,6 @@ pub async fn serve( let engine = service .graphql_engine() .ok_or_else(|| std::io::Error::other("serve requires GraphQL"))?; - let ingress = service.clone(); - let scrape = service.clone(); let commands: Vec = service .command_names() .into_iter() @@ -108,33 +76,10 @@ pub async fn serve( async move { Json(body) } }), ); - let mut internal = Router::new() - .route( - "/zitadel.ingress.v1", - post(move |headers: HeaderMap, Json(body): Json| { - let svc = ingress.clone(); - async move { - let caller = session_from_headers(&headers); - command_response( - zitadel::COMMAND, - zitadel::receive(&svc, &caller, body).await, - ) - } - }), - ) - .route( - "/zitadel.scrape.v1", - post(move |headers: HeaderMap| { - let svc = scrape.clone(); - async move { - let caller = session_from_headers(&headers); - command_response( - zitadel_scrape::COMMAND, - zitadel_scrape::receive(&svc, &caller).await, - ) - } - }), - ); + // The commands the service exposes (the Zitadel ingress and scrape, each + // through its own edge) and the Queue relay are internal: the cell + // secret first, then each edge's own check. + let mut internal = microsvc::command_router(service.clone()).with_state(service.clone()); internal = internal.route( CELLD_QUEUE_RELAY_PATH, post(move |Json(envelope): Json| { @@ -168,28 +113,16 @@ pub async fn serve( Route::new("graphql", RoutePath::prefix("/graphql"), "graphql"), Route::new("ui", RoutePath::prefix("/"), "ui"), ]; - for path in [ - "/health", - "/zitadel.ingress.v1", - "/zitadel.scrape.v1", - CELLD_QUEUE_RELAY_PATH, - ] { + for path in ["/health", CELLD_QUEUE_RELAY_PATH] { routes.push(Route::new( format!("service-{}", routes.len()), RoutePath::exact(path), "service", )); } - for command in service.command_names() { - let path = RoutePath::exact(format!("/{command}")); - if !routes.iter().any(|route| route.path == path) { - routes.push(Route::new( - format!("closed-{}", routes.len()), - path, - "closed", - )); - } - } + // Every command path is the service's: it answers the exposed Zitadel + // commands, and no other command URL can become UI HTML. + routes.extend(service.command_gateway_routes("service")); let gateway = GatewayConfig { bindings: vec![ Binding::new( @@ -208,7 +141,6 @@ pub async fn serve( }, ), Binding::new("service", BindingKind::Handler), - Binding::new("closed", BindingKind::Handler), ], routes, } @@ -238,7 +170,6 @@ pub async fn serve( ), ("ui".into(), NativeBinding::UiProxy { websocket: true }), ("service".into(), NativeBinding::Handler(app)), - ("closed".into(), NativeBinding::Handler(Router::new())), ], auth, ) diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs b/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs index e4d83c23d..e23dbe448 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/compose.rs @@ -11,6 +11,7 @@ use crate::modules::projections; use e2e_celld_blob as blob; use e2e_celld_chat as chat; use e2e_celld_identity as identity; +use e2e_celld_identity::handlers::ingestors::{zitadel, zitadel_scrape}; use e2e_celld_todo as todo; /// Explicit module inventory for the celld example (same ids as e2e-ui so the UI client matches). @@ -60,15 +61,18 @@ where projections.chat, ); let blob = blob::routes(repo.clone(), locks, read_models.clone(), projections.blob); - let identity = identity::routes(repo, read_models); + let identity = identity::routes(repo, read_models, projections.auth); // GraphQL-only public write surface. POST /todo.* stays 404 (suite T0). - // Zitadel Action ingress is the identity crate; `http::serve` gives its - // commands an authenticating edge. + // Zitadel Action ingress is the identity crate: its two commands are + // exposed through edges that check the shared secret and run as the + // ingestor (`http::serve` also requires the cell internal secret). Service::new() .named("e2e-ui") .routes(todos) .routes(chat) .routes(blob) .routes(identity) + .with_http_command(zitadel::COMMAND, zitadel::http_edge) + .with_http_command(zitadel_scrape::COMMAND, zitadel_scrape::http_edge) } diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs index d714a81ce..1d7ae8a10 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs @@ -70,6 +70,7 @@ pub(crate) fn build_graphql_engine_with_graphiql( projections.todo.into(), projections.chat.into(), projections.blob.into(), + projections.auth.into(), ]) .identity(identity) .graphiql(graphiql); @@ -114,6 +115,7 @@ fn pool_free_full_surface() -> Surface { projections.todo.into(), projections.chat.into(), projections.blob.into(), + projections.auth.into(), ]) .expect("e2e-celld projector topology should bind") .with_service(&service) diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs b/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs index 69b4723c7..cc42d236d 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/projections.rs @@ -5,8 +5,8 @@ use distributed::graphql::{SurfaceDirectProjection, SurfaceProjector}; use distributed::LocalProjectionMountsBuilder; -use e2e_projections::{BLOB_GAMES, CHAT_MESSAGES, TODOS}; -use e2e_readmodels::{BlobGames, ChatMessages, Todos}; +use e2e_projections::{AUTH_USERS, BLOB_GAMES, CHAT_MESSAGES, TODOS}; +use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; /// Projection surface mounts used by compose + GraphQL. #[derive(Clone)] @@ -14,6 +14,7 @@ pub struct ProjectionOwners { pub todo: SurfaceProjector, pub chat: SurfaceProjector, pub blob: SurfaceDirectProjection, + pub auth: SurfaceProjector, } /// Compile local projection mounts for the e2e-ui application. @@ -26,18 +27,21 @@ pub fn projection_owners() -> ProjectionOwners { .expect("chat mount") .direct_model::("project_blob", BLOB_GAMES, "e2e-ui-blob-v2") .expect("blob mount") + .eventual_model::("project_auth_users", AUTH_USERS, "e2e-ui-auth-users-v1") + .expect("auth users mount") .build() .expect("projection catalog"); ProjectionOwners { - todo: mounts - .projector("project_todos") - .expect("todo projector"), + todo: mounts.projector("project_todos").expect("todo projector"), chat: mounts .projector("project_chat_messages") .expect("chat projector"), blob: mounts .direct_projection("project_blob") .expect("blob direct"), + auth: mounts + .projector("project_auth_users") + .expect("auth users projector"), } } diff --git a/tests/e2e-celld/crates/identity-service/Cargo.toml b/tests/e2e-celld/crates/identity-service/Cargo.toml index 760d0444f..080a30bc2 100644 --- a/tests/e2e-celld/crates/identity-service/Cargo.toml +++ b/tests/e2e-celld/crates/identity-service/Cargo.toml @@ -3,10 +3,11 @@ name = "e2e-celld-identity" version.workspace = true edition.workspace = true publish = false -description = "Zitadel identity ingestor + AuthUsers projector (in-process; not a cell)" +description = "Zitadel identity ingestor + AuthUsers projection (in-process; not a cell)" [dependencies] distributed = { workspace = true } +axum = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } diff --git a/tests/e2e-celld/crates/identity-service/src/deps.rs b/tests/e2e-celld/crates/identity-service/src/deps.rs index 3cadf3c9a..9d0534046 100644 --- a/tests/e2e-celld/crates/identity-service/src/deps.rs +++ b/tests/e2e-celld/crates/identity-service/src/deps.rs @@ -1,5 +1,6 @@ use distributed::microsvc::RepoReadModelDependencies; use distributed::AggregateRepository; -/// Stores, no aggregate: the commands publish provider messages only. +/// Stores, no aggregate: the commands publish user profiles, which the +/// auth_users projection writes. pub type AuthDeps = RepoReadModelDependencies, S>; diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/events/mod.rs b/tests/e2e-celld/crates/identity-service/src/handlers/events/mod.rs deleted file mode 100644 index 6e55e44fc..000000000 --- a/tests/e2e-celld/crates/identity-service/src/handlers/events/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod project_auth_user; diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/events/project_auth_user.rs b/tests/e2e-celld/crates/identity-service/src/handlers/events/project_auth_user.rs deleted file mode 100644 index 3202f046c..000000000 --- a/tests/e2e-celld/crates/identity-service/src/handlers/events/project_auth_user.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! Project `zitadel.user.*.v1` → `auth_users` (join target for chat + blob games). - -use distributed::microsvc::{Context, HandlerError}; -use distributed::read_model::ReadModelWritePlanBuilder; -use e2e_projections::{map_zitadel_user_status, map_zitadel_user_upsert, ZitadelUserPayload}; -use serde_json::{json, Value}; - -use crate::deps::AuthDeps; -use crate::handlers::util::{decode_payload, read_model_error}; - -pub const EVENTS: &[&str] = &[ - "zitadel.user.human.created.v1", - "zitadel.user.human.updated.v1", - "zitadel.user.human.deactivated.v1", - "zitadel.user.human.reactivated.v1", - "zitadel.user.machine.created.v1", -]; - -pub fn guard(_ctx: &Context>) -> bool -where - R: crate::bounds::EventStore, - S: crate::bounds::ReadStore, -{ - true -} - -pub async fn handle(ctx: &Context<'_, AuthDeps>) -> Result -where - R: crate::bounds::EventStore, - S: crate::bounds::ReadStore, -{ - let payload: ZitadelUserPayload = decode_payload(ctx.message())?; - let name = ctx.message().name(); - let row = if name.contains("deactivated") || name.contains("reactivated") { - map_zitadel_user_status(name, &payload) - } else { - map_zitadel_user_upsert(name, &payload) - }; - - let store = ctx.read_model_store(); - let mut plan = ReadModelWritePlanBuilder::new(); - plan.upsert(&row).map_err(read_model_error)?; - plan.commit(store).await.map_err(read_model_error)?; - - Ok(json!({ - "event": name, - "user_id": row.user_id, - "status": row.status, - "display_name": row.display_name, - })) -} diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/auth.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/auth.rs index 023fb7729..67f292a86 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/auth.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/auth.rs @@ -6,13 +6,14 @@ use std::env; +use axum::http::HeaderMap; use distributed::command_dispatch::VerifiedPrincipal; use distributed::microsvc::{HandlerError, Session, ROLE_KEY, USER_ID_KEY}; /// Env var for the shared secret (required for fixture/curl path). pub const SECRET_ENV: &str = "ZITADEL_INGESTOR_SECRET"; -/// Preferred Action/HTTP header (lowercase session keys). +/// Preferred Action/HTTP header. pub const SECRET_HEADER: &str = "x-zitadel-ingestor-secret"; /// When `1`/`true`, accept native Actions v2 event envelopes without shared secret. @@ -54,11 +55,12 @@ pub fn allow_action_events() -> bool { ) } -pub fn presented_secret(session: &Session) -> Option { - if let Some(v) = session.get(SECRET_HEADER).filter(|s| !s.is_empty()) { +pub fn presented_secret(headers: &HeaderMap) -> Option { + let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()); + if let Some(v) = header(SECRET_HEADER).filter(|s| !s.is_empty()) { return Some(v.to_string()); } - if let Some(auth) = session.get("authorization") { + if let Some(auth) = header("authorization") { if let Some(token) = auth .strip_prefix("Bearer ") .or_else(|| auth.strip_prefix("bearer ")) @@ -72,8 +74,11 @@ pub fn presented_secret(session: &Session) -> Option { None } -pub fn verify_authenticity(session: &Session, is_action_event: bool) -> Result<(), HandlerError> { - if let Some(presented) = presented_secret(session) { +/// Whether the request with `headers` may run an ingestor command: it +/// presents the configured secret, or it is an Actions v2 event body +/// (`is_action_event`) and those are allowed. +pub fn verify_authenticity(headers: &HeaderMap, is_action_event: bool) -> Result<(), HandlerError> { + if let Some(presented) = presented_secret(headers) { let expected = configured_secret().ok_or_else(|| { HandlerError::Unauthorized(format!( "{SECRET_ENV} is not configured; refusing Zitadel ingress" @@ -110,7 +115,6 @@ pub fn verify_authenticity(session: &Session, is_action_event: bool) -> Result<( #[cfg(test)] pub(super) mod tests { use super::*; - use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; static ENV_LOCK: Mutex<()> = Mutex::new(()); @@ -161,18 +165,18 @@ pub(super) mod tests { f(); } - fn session(pairs: &[(&str, &str)]) -> Session { - let mut m = HashMap::new(); - for (k, v) in pairs { - m.insert((*k).to_string(), (*v).to_string()); + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert(*name, value.parse().unwrap()); } - Session::from_map(m) + headers } #[test] fn rejects_when_secret_not_configured() { with_env(None, false, || { - let err = verify_authenticity(&session(&[(SECRET_HEADER, "x")]), false).unwrap_err(); + let err = verify_authenticity(&headers(&[(SECRET_HEADER, "x")]), false).unwrap_err(); assert!(matches!(err, HandlerError::Unauthorized(_))); }); } @@ -180,14 +184,26 @@ pub(super) mod tests { #[test] fn accepts_matching_header() { with_env(Some("s3cret"), false, || { - verify_authenticity(&session(&[(SECRET_HEADER, "s3cret")]), false).unwrap(); + verify_authenticity(&headers(&[(SECRET_HEADER, "s3cret")]), false).unwrap(); }); } #[test] fn accepts_action_event_when_allowed() { with_env(None, true, || { - verify_authenticity(&Session::new(), true).unwrap(); + verify_authenticity(&HeaderMap::new(), true).unwrap(); + }); + } + + #[test] + fn accepts_matching_bearer_and_rejects_a_wrong_secret() { + with_env(Some("s3cret"), true, || { + verify_authenticity(&headers(&[("authorization", "Bearer s3cret")]), false).unwrap(); + // A wrong secret is refused even for an allowed Action event body. + let err = verify_authenticity(&headers(&[(SECRET_HEADER, "nope")]), true).unwrap_err(); + assert!(matches!(err, HandlerError::Unauthorized(_))); + let err = verify_authenticity(&HeaderMap::new(), false).unwrap_err(); + assert!(matches!(err, HandlerError::Unauthorized(_))); }); } } diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/handle.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/handle.rs index 7549b096f..0502dc6ed 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/handle.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/handle.rs @@ -1,12 +1,14 @@ -//! Command: `zitadel.ingress.v1` — map one provider delivery and publish its -//! provider message. No aggregate: the message commits with the command's -//! ledger receipt. +//! Command: `zitadel.ingress.v1` — map one provider delivery and publish the +//! user's profile. No aggregate: the profile is an external fact, committed +//! with the command's ledger receipt and projected into `auth_users`. +use axum::http::HeaderMap; use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use distributed::command_dispatch::deterministic_command_id; use distributed::microsvc::{ - CausalCommandContext, CausalDispatchError, HandlerError, Service, Session, + CausalCommandContext, CausalDispatchError, HandlerError, HttpCommandDispatch, }; +use distributed::ExternalEventSource; use serde::Serialize; use serde_json::Value; @@ -14,14 +16,14 @@ use super::auth::{ingestor_principal, ingestor_session, verify_authenticity, ING use super::map::{ looks_like_action_event, map_action_delivery, normalize_ingress_body, ZitadelIngressInput, }; -use super::publish::provider_message; /// Command name, and the path of its HTTP edge (POST `/{COMMAND}`). pub const COMMAND: &str = "zitadel.ingress.v1"; #[derive(Debug, Serialize, distributed::CommandOutput)] pub struct ZitadelIngressPayload { - /// Provider message published; `None` when the event type maps to none. + /// Provider event the delivery was; `None` when the event type maps to + /// none, and nothing was published. pub published: Option, /// Why nothing was published. pub skipped: Option, @@ -53,20 +55,26 @@ pub async fn handle( .map_err(|error| HandlerError::Other(Box::new(error))); }; - // Provider envelope only — the projector maps it to auth_users. - let command_id = ctx.message_id().unwrap_or_default(); - let message = provider_message(format!("{COMMAND}:{command_id}"), &mapped)?; - ctx.outbox(message) + // The profile is identified by this command: a redelivery is this + // command again, and another command never publishes the same fact. + let source = ExternalEventSource { + producer: COMMAND.into(), + stream: ctx.message_id().unwrap_or_default().into(), + position: 1, + key: mapped.profile.user_id.clone(), + }; + let payload = ZitadelIngressPayload { + published: Some(mapped.message_name), + skipped: None, + event_type: input.event_type, + event_id: Some(mapped.delivery_id), + provider_subject: Some(mapped.profile.user_id.clone()), + user_kind: Some(mapped.profile.user_kind.clone()), + approval_status: Some(mapped.profile.approval_status.clone()), + }; + ctx.publish_external(source, mapped.profile) .commit()? - .succeeded(ZitadelIngressPayload { - published: Some(mapped.message_name), - skipped: None, - event_type: input.event_type, - event_id: Some(mapped.delivery_id), - provider_subject: Some(mapped.payload.provider_subject), - user_kind: Some(mapped.payload.user_kind), - approval_status: Some(mapped.payload.approval_status), - }) + .succeeded(payload) } /// The ledger command id of one delivery. Zitadel delivers an event again @@ -86,15 +94,14 @@ pub fn ingress_command_id(input: &ZitadelIngressInput) -> String { } } -/// HTTP edge of [`COMMAND`]: authenticate the caller, then dispatch the -/// delivery as the ingestor. `caller` is the request's headers; none of them +/// HTTP edge of [`COMMAND`] (`Service::with_http_command`): authenticate the +/// caller, then dispatch the delivery as the ingestor. No request header /// reaches the command. -pub async fn receive( - service: &Service, - caller: &Session, +pub fn http_edge( + headers: &HeaderMap, body: Value, -) -> Result { - verify_authenticity(caller, looks_like_action_event(&body)) +) -> Result { + verify_authenticity(headers, looks_like_action_event(&body)) .map_err(CausalDispatchError::Handler)?; if body.is_null() { return Err(CausalDispatchError::BadRequest( @@ -105,52 +112,67 @@ pub async fn receive( let command_id = ingress_command_id(&input); let input = serde_json::to_value(input) .map_err(|error| CausalDispatchError::Internal(error.to_string()))?; - service - .dispatch_causal( - COMMAND, - &command_id, - input, - ingestor_session(), - ingestor_principal(), - ) - .await + Ok(HttpCommandDispatch { + command_id, + input, + session: ingestor_session(), + principal: ingestor_principal(), + }) } #[cfg(test)] mod tests { + use std::sync::Arc; + use super::super::auth::tests::IngestorEnv; use super::super::auth::SECRET_HEADER; - use super::super::map::HUMAN_CREATED; use super::*; - use distributed::microsvc::Routes; + use distributed::microsvc::{self, Routes, Service}; use distributed::{InMemoryRepository, OutboxStore}; + use e2e_projections::ZitadelUserProfile; use serde_json::json; - fn caller(secret: &str) -> Session { - let mut caller = Session::new(); - caller.set(SECRET_HEADER, secret); - caller - } - - async fn provider_messages(repo: &InMemoryRepository) -> usize { + /// The `zitadel.user_profile` facts in the outbox. + async fn published_profiles(repo: &InMemoryRepository) -> Vec { repo.outbox_store() .pending(usize::MAX) .await .unwrap() .iter() - .filter(|message| message.event_type == HUMAN_CREATED) - .count() + .filter_map(|message| message.domain_event_occurrence().ok()) + .map(|occurrence| occurrence.decode_body().unwrap()) + .collect() + } + + async fn post(base: &str, secret: &str, body: &Value) -> (u16, Value) { + let response = reqwest::Client::new() + .post(format!("{base}/{COMMAND}")) + .header(SECRET_HEADER, secret) + // A caller-chosen identity never reaches the command. + .header("x-user-id", "attacker") + .json(body) + .send() + .await + .unwrap(); + (response.status().as_u16(), response.json().await.unwrap()) } #[tokio::test] - async fn a_redelivered_webhook_publishes_one_provider_message() { + async fn a_redelivered_webhook_publishes_one_profile() { let _env = IngestorEnv::set(Some("s3cret"), false); let repo = InMemoryRepository::new(); - let service = Service::new().named("identity").routes( - Routes::for_stores(repo.clone(), repo.clone()) - .typed_command(command()) - .handle(handle), - ); + let service = Service::new() + .named("identity") + .routes( + Routes::for_stores(repo.clone(), repo.clone()) + .typed_command(command()) + .handle(handle), + ) + .with_http_command(COMMAND, http_edge); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let app = microsvc::router(Arc::new(service)); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let delivery = json!({ "event_id": "evt-1", "event_type": "user.human.created", @@ -160,29 +182,24 @@ mod tests { }); // A caller without the secret runs no command. - let refused = receive(&service, &caller("wrong"), delivery.clone()).await; - assert!( - matches!( - refused, - Err(CausalDispatchError::Handler(HandlerError::Unauthorized(_))) - ), - "{refused:?}" - ); - assert_eq!(provider_messages(&repo).await, 0); - - let first = receive(&service, &caller("s3cret"), delivery.clone()) - .await - .unwrap(); - assert_eq!(first["published"], HUMAN_CREATED); - assert_eq!(first["event_id"], "evt-1"); - assert_eq!(provider_messages(&repo).await, 1); + let (status, refused) = post(&base, "wrong", &delivery).await; + assert_eq!(status, 401, "{refused}"); + assert!(published_profiles(&repo).await.is_empty()); + + let (status, first) = post(&base, "s3cret", &delivery).await; + assert_eq!(status, 200, "{first}"); + assert_eq!(first["payload"]["published"], super::super::HUMAN_CREATED); + assert_eq!(first["payload"]["event_id"], "evt-1"); + let profiles = published_profiles(&repo).await; + assert_eq!(profiles.len(), 1); + assert_eq!(profiles[0].user_id, "sub-1"); + assert_eq!(profiles[0].display_name, "Ada"); + assert_eq!(profiles[0].status, "active"); // The provider delivers the event again: the stored receipt answers. - let again = receive(&service, &caller("s3cret"), delivery) - .await - .unwrap(); + let (_, again) = post(&base, "s3cret", &delivery).await; assert_eq!(again, first); - assert_eq!(provider_messages(&repo).await, 1); + assert_eq!(published_profiles(&repo).await.len(), 1); // One delivery id for another event is refused, not published. let other = json!({ @@ -190,11 +207,8 @@ mod tests { "event_type": "user.human.created", "user_id": "sub-2", }); - let reused = receive(&service, &caller("s3cret"), other).await; - assert!( - matches!(reused, Err(CausalDispatchError::CommandIdReuse)), - "{reused:?}" - ); - assert_eq!(provider_messages(&repo).await, 1); + let (status, reused) = post(&base, "s3cret", &other).await; + assert_eq!(status, 409, "{reused}"); + assert_eq!(published_profiles(&repo).await.len(), 1); } } diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/map.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/map.rs index 5e351e733..acf52bb8c 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/map.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/map.rs @@ -1,6 +1,7 @@ -//! Map Zitadel Action / fixture payloads → provider bus subjects + envelopes. +//! Map Zitadel Action / fixture payloads → the provider event they name and +//! the user profile they carry. -use e2e_projections::{ZitadelEmail, ZitadelUserPayload}; +use e2e_projections::ZitadelUserProfile; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -38,11 +39,49 @@ pub struct ZitadelIngressEmail { pub verified: Option, } +/// One provider delivery: which Zitadel event it is, and the user's profile +/// after it. #[derive(Debug, Clone)] pub struct MappedDelivery { pub message_name: String, pub delivery_id: String, - pub payload: ZitadelUserPayload, + pub profile: ZitadelUserProfile, +} + +/// The profile a provider event leaves a user with. A deactivation leaves +/// them `deactivated`, every other event `active`; an empty display name +/// falls back to the email, then the subject. +pub fn user_profile( + message_name: &str, + user_id: &str, + user_kind: String, + email: String, + display_name: Option, + approval_status: String, +) -> ZitadelUserProfile { + let display_name = display_name + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| { + if email.is_empty() { + user_id.to_string() + } else { + email.clone() + } + }); + let status = if message_name == HUMAN_DEACTIVATED { + "deactivated" + } else { + "active" + }; + ZitadelUserProfile { + user_id: user_id.to_string(), + email, + display_name, + user_kind, + approval_status, + status: status.into(), + updated_at: now_ms(), + } } pub fn looks_like_action_event(raw: &Value) -> bool { @@ -203,26 +242,20 @@ pub fn map_action_delivery(input: &ZitadelIngressInput) -> Option) -> Option<&'s None } -fn normalize_emails(input: &ZitadelIngressInput) -> Vec { - if let Some(list) = &input.emails { - if !list.is_empty() { - return list - .iter() - .map(|e| ZitadelEmail { - address: e.address.clone(), - primary: e.primary.unwrap_or(false), - verified: e.verified.unwrap_or(true), - }) - .collect(); - } - } - if let Some(email) = input.email.as_ref().filter(|s| !s.trim().is_empty()) { - return vec![ZitadelEmail { - address: email.clone(), - primary: true, - verified: true, - }]; +/// The delivery's primary email (the first listed when none is marked), or +/// its single `email`; empty when it has none. +fn primary_email(input: &ZitadelIngressInput) -> String { + let listed = input.emails.iter().flatten(); + if let Some(email) = listed + .clone() + .find(|email| email.primary == Some(true)) + .or_else(|| listed.clone().next()) + { + return email.address.clone(); } - Vec::new() + input + .email + .clone() + .filter(|email| !email.trim().is_empty()) + .unwrap_or_default() } fn derive_approval(input: &ZitadelIngressInput, user_kind: &str) -> String { @@ -325,12 +353,12 @@ fn derive_approval(input: &ZitadelIngressInput, user_kind: &str) -> String { } } -fn now_rfc3339ish() -> String { +/// Milliseconds since the epoch: a sortable timestamp without chrono. +fn now_ms() -> String { use std::time::{SystemTime, UNIX_EPOCH}; let d = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default(); - // Sortable timestamp without chrono dependency. format!("{}", d.as_millis()) } @@ -356,9 +384,11 @@ mod tests { let m = map_action_delivery(&input).expect("mapped"); assert_eq!(m.message_name, HUMAN_CREATED); assert_eq!(m.delivery_id, "d1"); - assert_eq!(m.payload.approval_status, "pending"); - assert_eq!(m.payload.user_kind, "human"); - assert_eq!(m.payload.emails[0].address, "ada@example.com"); + assert_eq!(m.profile.approval_status, "pending"); + assert_eq!(m.profile.user_kind, "human"); + assert_eq!(m.profile.email, "ada@example.com"); + assert_eq!(m.profile.display_name, "Ada"); + assert_eq!(m.profile.status, "active"); } #[test] @@ -377,7 +407,7 @@ mod tests { }; let m = map_action_delivery(&input).unwrap(); assert_eq!(m.message_name, HUMAN_UPDATED); - assert_eq!(m.payload.approval_status, "approved"); + assert_eq!(m.profile.approval_status, "approved"); } #[test] @@ -414,6 +444,47 @@ mod tests { assert_eq!(d.provider_subject.as_deref(), Some("user-99")); let m = map_action_delivery(&d).expect("mapped"); assert_eq!(m.message_name, HUMAN_CREATED); - assert_eq!(m.payload.provider_subject, "user-99"); + assert_eq!(m.profile.user_id, "user-99"); + } + + #[test] + fn a_deactivation_leaves_the_user_deactivated_and_names_fall_back() { + let input = ZitadelIngressInput { + delivery_id: Some("d4".into()), + event_type: Some("user.human.deactivated".into()), + provider_subject: Some("sub-1".into()), + user_kind: None, + email: None, + emails: Some(vec![ + ZitadelIngressEmail { + address: "old@example.com".into(), + primary: None, + verified: None, + }, + ZitadelIngressEmail { + address: "ada@example.com".into(), + primary: Some(true), + verified: None, + }, + ]), + display_name: Some(" ".into()), + approval_status: None, + grants: None, + roles: None, + }; + let m = map_action_delivery(&input).unwrap(); + assert_eq!(m.message_name, HUMAN_DEACTIVATED); + assert_eq!(m.profile.status, "deactivated"); + assert_eq!(m.profile.email, "ada@example.com"); + assert_eq!(m.profile.display_name, "ada@example.com"); + + let reactivated = map_action_delivery(&ZitadelIngressInput { + event_type: Some("user.human.reactivated".into()), + emails: None, + ..input + }) + .unwrap(); + assert_eq!(reactivated.profile.status, "active"); + assert_eq!(reactivated.profile.display_name, "sub-1"); } } diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/mod.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/mod.rs index b60eeb03f..ad61970af 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/mod.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/mod.rs @@ -1,12 +1,14 @@ -//! Zitadel Action/HTTP ingress + Management API scrape → provider messages only. +//! Zitadel Action/HTTP ingress + Management API scrape → user profiles. //! //! Teaching fixture (simplified from gitkb domain-service): -//! 1. Authenticity (`auth`) — shared secret header, checked at the HTTP edge; -//! it vouches for the ingestor identity the commands run as -//! 2. Map (`map`) — Action payload → typed `zitadel.*.v1` subjects -//! 3. Publish (`publish`) — outbox provider message, committed with the -//! command's ledger receipt (no aggregate) -//! 4. Projector (`project_auth_user`) — upserts `auth_users` for GraphQL joins +//! 1. Authenticity (`auth`) — shared secret header, checked by the command's +//! HTTP edge; it vouches for the ingestor identity the commands run as +//! 2. Map (`map`) — Action payload → the `zitadel.*.v1` event it is and the +//! user's [`ZitadelUserProfile`](e2e_projections::ZitadelUserProfile) +//! 3. Publish — `publish_external`: the profile as an external fact, +//! committed with the command's ledger receipt (no aggregate) +//! 4. Projection (`e2e_projections::AUTH_USERS`) — upserts `auth_users` for +//! GraphQL joins //! 5. Scrape (`scrape`) — periodic Management API reconcile for missed events //! //! See `docs/zitadel-ingestor.md`. @@ -14,7 +16,6 @@ mod auth; mod handle; mod map; -mod publish; pub mod scrape; pub use auth::{ @@ -22,36 +23,12 @@ pub use auth::{ verify_authenticity, ALLOW_ACTION_EVENTS_ENV, INGESTOR_ROLE, INGESTOR_USER_ID, SECRET_ENV, SECRET_HEADER, }; -pub use handle::{command, handle, ingress_command_id, receive, ZitadelIngressPayload, COMMAND}; +pub use handle::{command, handle, http_edge, ingress_command_id, ZitadelIngressPayload, COMMAND}; pub use map::{ - looks_like_action_event, map_action_delivery, normalize_ingress_body, MappedDelivery, - ZitadelIngressEmail, ZitadelIngressInput, HUMAN_CREATED, HUMAN_DEACTIVATED, HUMAN_REACTIVATED, - HUMAN_UPDATED, MACHINE_CREATED, + looks_like_action_event, map_action_delivery, normalize_ingress_body, user_profile, + MappedDelivery, ZitadelIngressEmail, ZitadelIngressInput, HUMAN_CREATED, HUMAN_DEACTIVATED, + HUMAN_REACTIVATED, HUMAN_UPDATED, MACHINE_CREATED, }; -pub use publish::provider_message; pub use scrape::{ spawn_scrape_loop, ZitadelScrapeConfig, API_URL_ENV, INTERVAL_ENV, ON_START_ENV, TOKEN_ENV, }; - -/// Provider event names published by this ingestor (never domain forgeries). -pub fn is_provider_message_name(name: &str) -> bool { - name.starts_with("zitadel.") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn provider_names_are_zitadel_prefixed() { - for name in [ - HUMAN_CREATED, - HUMAN_UPDATED, - HUMAN_DEACTIVATED, - HUMAN_REACTIVATED, - MACHINE_CREATED, - ] { - assert!(is_provider_message_name(name), "{name}"); - } - } -} diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/publish.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/publish.rs deleted file mode 100644 index b87415745..000000000 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/publish.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Provider message encoding shared by ingress and scrape. - -use distributed::microsvc::HandlerError; -use distributed::OutboxMessage; - -use super::map::MappedDelivery; - -/// Encode a mapped provider delivery as the outbox message `id`. -/// -/// Callers derive `id` from their command id, so one command never stages an -/// id another command committed. -pub fn provider_message( - id: String, - mapped: &MappedDelivery, -) -> Result { - OutboxMessage::encode(id, mapped.message_name.as_str(), &mapped.payload) - .map_err(|error| HandlerError::Other(Box::new(error))) -} diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/scrape.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/scrape.rs index 38606d7ef..c64105329 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/scrape.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel/scrape.rs @@ -9,14 +9,10 @@ use std::sync::Arc; use std::time::Duration; use distributed::microsvc::Service; -use e2e_projections::{ - map_zitadel_user_status, map_zitadel_user_upsert, ZitadelEmail, ZitadelUserPayload, -}; -use e2e_readmodels::AuthUsers; use serde::Deserialize; use serde_json::{json, Value}; -use super::map::{MappedDelivery, HUMAN_DEACTIVATED, HUMAN_UPDATED, MACHINE_CREATED}; +use super::map::{user_profile, MappedDelivery, HUMAN_DEACTIVATED, HUMAN_UPDATED, MACHINE_CREATED}; /// Env: Management API base (no trailing slash). Falls back to `OIDC_ISSUER`. pub const API_URL_ENV: &str = "ZITADEL_API_URL"; @@ -99,17 +95,6 @@ pub async fn list_mapped_users( )) } -/// The `auth_users` row of a listed user: what the projector writes for the -/// same provider message. -pub fn auth_user_row(mapped: &MappedDelivery) -> AuthUsers { - let name = mapped.message_name.as_str(); - if name.contains("deactivated") || name.contains("reactivated") { - map_zitadel_user_status(name, &mapped.payload) - } else { - map_zitadel_user_upsert(name, &mapped.payload) - } -} - #[derive(Debug, Clone, Deserialize)] struct SearchResponse { #[serde(default)] @@ -161,8 +146,6 @@ struct MgmtProfile { struct MgmtEmail { #[serde(default)] email: Option, - #[serde(default, rename = "isEmailVerified")] - is_email_verified: Option, } #[derive(Debug, Clone, Deserialize)] @@ -291,39 +274,20 @@ fn map_mgmt_user(user: &MgmtUser) -> Option { let fingerprint = simple_fingerprint(&[&email, &display_name, state, &user_kind, &change]); let delivery_id = format!("zitadel-scrape:{id}:{fingerprint}"); - let emails = if email.is_empty() { - Vec::new() - } else { - vec![ZitadelEmail { - address: email, - primary: true, - verified: user - .human - .as_ref() - .and_then(|h| h.email.as_ref()) - .and_then(|e| e.is_email_verified) - .unwrap_or(true), - }] - }; - - let payload = ZitadelUserPayload { - schema_version: 1, - source: "zitadel-scrape".into(), - delivery_id: delivery_id.clone(), - provider: "zitadel".into(), - provider_subject: id.to_string(), + let profile = user_profile( + message_name, + id, user_kind, - emails, - display_name: Some(display_name), + email, + Some(display_name), // Scrape treats every listed identity as a directory member. - approval_status: "approved".into(), - ingested_at: now_ms(), - }; + "approved".into(), + ); Some(MappedDelivery { message_name: message_name.to_string(), delivery_id, - payload, + profile, }) } @@ -341,14 +305,6 @@ fn simple_fingerprint(parts: &[&str]) -> String { format!("{hash:016x}") } -fn now_ms() -> String { - use std::time::{SystemTime, UNIX_EPOCH}; - let d = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - format!("{}", d.as_millis()) -} - /// Background loop: optional immediate scrape, then every `cfg.interval`. /// Each scrape is one `zitadel.scrape.v1` command on `service`. pub fn spawn_scrape_loop(service: Arc, cfg: ZitadelScrapeConfig) { @@ -395,9 +351,10 @@ mod tests { }); let m = map_management_user(&raw).expect("mapped"); assert_eq!(m.message_name, HUMAN_UPDATED); - assert_eq!(m.payload.provider_subject, "user-1"); - assert_eq!(m.payload.display_name.as_deref(), Some("Alice")); - assert_eq!(m.payload.emails[0].address, "alice@e2e.local"); + assert_eq!(m.profile.user_id, "user-1"); + assert_eq!(m.profile.display_name, "Alice"); + assert_eq!(m.profile.email, "alice@e2e.local"); + assert_eq!(m.profile.approval_status, "approved"); assert!(m.delivery_id.starts_with("zitadel-scrape:user-1:")); } @@ -413,6 +370,7 @@ mod tests { }); let m = map_management_user(&raw).unwrap(); assert_eq!(m.message_name, HUMAN_DEACTIVATED); + assert_eq!(m.profile.status, "deactivated"); } #[test] @@ -424,7 +382,7 @@ mod tests { }); let m = map_management_user(&raw).unwrap(); assert_eq!(m.message_name, MACHINE_CREATED); - assert_eq!(m.payload.user_kind, "machine"); + assert_eq!(m.profile.user_kind, "machine"); } #[test] diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel_scrape.rs b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel_scrape.rs index 3bad30484..88ab18100 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel_scrape.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/ingestors/zitadel_scrape.rs @@ -1,33 +1,30 @@ //! Command: `zitadel.scrape.v1` — reconcile from the Management API. //! -//! Lists every user and publishes the ones whose `auth_users` row differs -//! from the listed profile: one commit holds a provider message and the row -//! per changed user, with the command's receipt. No aggregate. Requires +//! Lists every user and publishes the profiles that differ from their +//! `auth_users` row, in one commit with the command's receipt; the +//! `auth_users` projection writes them. No aggregate. Requires //! `ZITADEL_SERVICE_USER_TOKEN` + `ZITADEL_API_URL` / `OIDC_ISSUER` in env. -use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use std::future::Future; use std::pin::Pin; +use axum::http::HeaderMap; +use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use distributed::microsvc::{ - CausalCommandContext, CausalDispatchError, HandlerError, PreparedCommandHandler, Service, - Session, + CausalCommandContext, CausalDispatchError, HandlerError, HttpCommandDispatch, + PreparedCommandHandler, Service, }; -use distributed::read_model::ReadModelWritePlanBuilder; use distributed::{ - ReadModelWorkspaceExt, ReadModelWritePlanStore, RelationalReadModelQueryStore, RowKey, RowValue, + ExternalEventSource, ReadModelWorkspaceExt, ReadModelWritePlanStore, + RelationalReadModelQueryStore, RowKey, RowValue, }; use e2e_readmodels::AuthUsers; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use super::zitadel::scrape::{ - auth_user_row, list_mapped_users, ZitadelScrapeConfig, API_URL_ENV, TOKEN_ENV, -}; +use super::zitadel::scrape::{list_mapped_users, ZitadelScrapeConfig, API_URL_ENV, TOKEN_ENV}; use super::zitadel::MappedDelivery; -use super::zitadel::{ - ingestor_principal, ingestor_session, provider_message, verify_authenticity, INGESTOR_ROLE, -}; +use super::zitadel::{ingestor_principal, ingestor_session, verify_authenticity, INGESTOR_ROLE}; pub const COMMAND: &str = "zitadel.scrape.v1"; @@ -41,7 +38,7 @@ pub struct ZitadelScrapeInput { pub struct ZitadelScrapePayload { /// Users the Management API listed. pub listed: u32, - /// Provider messages published: one per user whose profile changed. + /// Profiles published: one per user whose profile changed. pub published: u32, /// Listed users not published: unchanged, or with no usable id. pub skipped: u32, @@ -86,23 +83,10 @@ where } } -/// Whether a listed profile must be published: its row is missing or differs. -/// -/// A scrape commits a user's row with that user's message, so an equal row -/// means the profile was already published. `updated_at` is when a profile was -/// ingested, not part of it. -pub fn profile_changed(listed: &AuthUsers, stored: Option<&AuthUsers>) -> bool { - stored.is_none_or(|stored| { - AuthUsers { - updated_at: listed.updated_at.clone(), - ..stored.clone() - } != *listed - }) -} - -/// Publish the `users` (of `listed`) whose profile changed, each with its -/// `auth_users` row. Directory joins (chat author, blob owner) do not wait for -/// the bus: the row commits here, with the message. +/// Publish the `users` (of `listed`) whose profile differs from their +/// `auth_users` row. A row equal to the listed profile means it was already +/// published and projected; a profile published but not yet projected is +/// published again, and the projection writes the same row twice. async fn reconcile( ctx: &CausalCommandContext<'_, ()>, read_models: &S, @@ -112,41 +96,47 @@ async fn reconcile( where S: ReadModelWritePlanStore + RelationalReadModelQueryStore, { - // Message ids come from this command's id, so a scrape never meets an id - // an earlier one committed. + // Each profile is identified by this command and its place in the + // listing, so a scrape never publishes a fact an earlier one did. let command_id = ctx.message_id().unwrap_or_default(); - let mut messages = Vec::new(); - let mut rows = ReadModelWritePlanBuilder::new(); + let mut changed = Vec::new(); for user in users { - let row = auth_user_row(user); - let key = RowKey::new([("user_id", RowValue::String(row.user_id.clone()))]); + let key = RowKey::new([("user_id", RowValue::String(user.profile.user_id.clone()))]); let stored = read_models .workspace() .load::(key) .one() .await .map_err(|error| HandlerError::Other(Box::new(error)))?; - if !profile_changed(&row, stored.as_ref().map(|stored| &stored.data)) { - continue; + if user + .profile + .differs_from(stored.as_ref().map(|stored| &stored.data)) + { + changed.push(user.profile.clone()); } - let id = format!("{COMMAND}:{command_id}:{}", messages.len()); - messages.push(provider_message(id, user)?); - rows.upsert(&row) - .map_err(|error| HandlerError::Other(Box::new(error)))?; } let payload = ZitadelScrapePayload { listed: listed as u32, - published: messages.len() as u32, - skipped: listed.saturating_sub(messages.len()) as u32, + published: changed.len() as u32, + skipped: listed.saturating_sub(changed.len()) as u32, }; - let mut messages = messages.into_iter(); - let Some(first) = messages.next() else { + let source = + |position: usize, profile: &e2e_projections::ZitadelUserProfile| ExternalEventSource { + producer: COMMAND.into(), + stream: command_id.into(), + position: position as u64 + 1, + key: profile.user_id.clone(), + }; + let mut changed = changed.into_iter().enumerate(); + let Some((position, first)) = changed.next() else { return PreparedCommand::prepare(payload) .map_err(|error| HandlerError::Other(Box::new(error))); }; - messages - .fold(ctx.outbox(first), |unit, message| unit.outbox(message)) - .read_models(rows) + changed + .fold( + ctx.publish_external(source(position, &first), first), + |unit, (position, profile)| unit.publish_external(source(position, &profile), profile), + ) .commit()? .succeeded(payload) } @@ -165,67 +155,45 @@ pub async fn scrape(service: &Service, trigger: &str) -> Result Result { - verify_authenticity(caller, false).map_err(CausalDispatchError::Handler)?; - scrape(service, "http").await +/// HTTP edge of [`COMMAND`] (`Service::with_http_command`): the shared +/// secret, then a scrape as the ingestor with a fresh id, like [`scrape`]. +/// The body is ignored and no request header reaches the command. +pub fn http_edge( + headers: &HeaderMap, + _body: Value, +) -> Result { + verify_authenticity(headers, false).map_err(CausalDispatchError::Handler)?; + Ok(HttpCommandDispatch { + command_id: uuid::Uuid::now_v7().to_string(), + input: json!({ "trigger": "http" }), + session: ingestor_session(), + principal: ingestor_principal(), + }) } #[cfg(test)] mod tests { - use super::super::zitadel::{HUMAN_UPDATED, MACHINE_CREATED}; + use super::super::zitadel::{user_profile, HUMAN_UPDATED}; use super::*; use distributed::microsvc::Routes; use distributed::{InMemoryRepository, OutboxStore}; - use e2e_projections::{ZitadelEmail, ZitadelUserPayload}; + use e2e_projections::{ZitadelUserProfile, AUTH_USERS}; - fn listed_user(subject: &str, display_name: &str, ingested_at: &str) -> MappedDelivery { + fn listed_user(subject: &str, display_name: &str) -> MappedDelivery { MappedDelivery { message_name: HUMAN_UPDATED.into(), delivery_id: format!("zitadel-scrape:{subject}"), - payload: ZitadelUserPayload { - schema_version: 1, - source: "zitadel-scrape".into(), - delivery_id: format!("zitadel-scrape:{subject}"), - provider: "zitadel".into(), - provider_subject: subject.into(), - user_kind: "human".into(), - emails: vec![ZitadelEmail { - address: format!("{subject}@example.com"), - primary: true, - verified: true, - }], - display_name: Some(display_name.into()), - approval_status: "approved".into(), - ingested_at: ingested_at.into(), - }, + profile: user_profile( + HUMAN_UPDATED, + subject, + "human".into(), + format!("{subject}@example.com"), + Some(display_name.into()), + "approved".into(), + ), } } - #[test] - fn a_profile_is_published_when_its_row_is_missing_or_differs() { - let listed = auth_user_row(&listed_user("ada", "Ada", "2")); - assert!(profile_changed(&listed, None)); - - // Only the ingestion time differs: the same profile. - let stored = auth_user_row(&listed_user("ada", "Ada", "1")); - assert!(!profile_changed(&listed, Some(&stored))); - - let renamed = auth_user_row(&listed_user("ada", "Ada L.", "1")); - assert!(profile_changed(&listed, Some(&renamed))); - let deactivated = AuthUsers { - status: "deactivated".into(), - ..stored.clone() - }; - assert!(profile_changed(&listed, Some(&deactivated))); - let pending = AuthUsers { - approval_status: "pending".into(), - ..stored - }; - assert!(profile_changed(&listed, Some(&pending))); - } - /// [`Scrape`] with the listing given, not fetched from Zitadel. struct Listed(InMemoryRepository, Vec); @@ -245,7 +213,7 @@ mod tests { } #[tokio::test] - async fn a_second_scrape_of_an_unchanged_listing_stages_nothing() { + async fn a_scrape_publishes_only_the_profiles_that_differ_from_their_rows() { let repo = InMemoryRepository::new(); let service_listing = |users: Vec| { Service::new().named("identity").routes( @@ -254,39 +222,61 @@ mod tests { .handle(Listed(repo.clone(), users)), ) }; - let staged = || async { + let published = || async { repo.outbox_store() .pending(usize::MAX) .await .unwrap() - .into_iter() - .map(|message| message.event_type) + .iter() + .map(|message| { + let occurrence = message.domain_event_occurrence().unwrap(); + assert_eq!(message.id(), occurrence.id()); + occurrence.decode_body::().unwrap() + }) + .map(|profile| (profile.user_id, profile.display_name)) .collect::>() }; - let users = vec![ - listed_user("ada", "Ada", "1"), - listed_user("grace", "Grace", "1"), - ]; + // Run the `auth_users` projection over everything published. + let project = || async { + for message in repo.outbox_store().pending(usize::MAX).await.unwrap() { + let occurrence = message.domain_event_occurrence().unwrap(); + let lowered = AUTH_USERS + .server_executor() + .unwrap() + .plan(&occurrence) + .unwrap(); + repo.commit_write_plan(lowered.write_plan).await.unwrap(); + } + }; + let users = vec![listed_user("ada", "Ada"), listed_user("grace", "Grace")]; // The listing also held one user with no usable id. let first = scrape(&service_listing(users.clone()), "start") .await .unwrap(); assert_eq!(first, json!({ "listed": 3, "published": 2, "skipped": 1 })); - assert_eq!(staged().await, [HUMAN_UPDATED, HUMAN_UPDATED]); + assert_eq!( + published().await, + [ + ("ada".into(), "Ada".into()), + ("grace".into(), "Grace".into()) + ] + ); + project().await; let unchanged = scrape(&service_listing(users), "interval").await.unwrap(); assert_eq!( unchanged, json!({ "listed": 3, "published": 0, "skipped": 3 }) ); - assert_eq!(staged().await.len(), 2); + assert_eq!(published().await.len(), 2); // One profile changed: that one alone is published. - let mut renamed = listed_user("grace", "Grace H.", "2"); - renamed.message_name = MACHINE_CREATED.into(); let changed = scrape( - &service_listing(vec![listed_user("ada", "Ada", "2"), renamed]), + &service_listing(vec![ + listed_user("ada", "Ada"), + listed_user("grace", "Grace H."), + ]), "interval", ) .await @@ -295,9 +285,6 @@ mod tests { changed, json!({ "listed": 3, "published": 1, "skipped": 2 }) ); - assert_eq!( - staged().await, - [HUMAN_UPDATED, HUMAN_UPDATED, MACHINE_CREATED] - ); + assert_eq!(published().await[2], ("grace".into(), "Grace H.".into())); } } diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs b/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs index e7d0ab091..033e0cc13 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/mod.rs @@ -1,3 +1,2 @@ -pub mod events; pub mod ingestors; pub mod util; diff --git a/tests/e2e-celld/crates/identity-service/src/handlers/util.rs b/tests/e2e-celld/crates/identity-service/src/handlers/util.rs index 9aa0154b2..1f4e6aca9 100644 --- a/tests/e2e-celld/crates/identity-service/src/handlers/util.rs +++ b/tests/e2e-celld/crates/identity-service/src/handlers/util.rs @@ -7,37 +7,13 @@ //! “am I logged in?” when a guard already did. //! - Domain owns entity invariants (empty title, ownership, board rules). -use distributed::bus::Message; use distributed::microsvc::{CausalCommandContext, HandlerError, Session}; -use distributed::{Aggregate, BitcodePayloadCodec, PayloadCodec}; -use serde::de::DeserializeOwned; - -/// Decode event payload as JSON (tests) or bitcode (outbox → bus). -pub fn decode_payload(message: &Message) -> Result { - let ct = message.content_type.as_str(); - if ct.contains("json") || looks_like_json(message.payload()) { - return serde_json::from_slice(message.payload()) - .map_err(|e| HandlerError::DecodeFailed(format!("json payload: {e}"))); - } - BitcodePayloadCodec::decode(message.payload()) - .map_err(|e| HandlerError::DecodeFailed(format!("bitcode payload: {e}"))) -} - -fn looks_like_json(bytes: &[u8]) -> bool { - matches!( - bytes.iter().find(|b| !b.is_ascii_whitespace()), - Some(b'{' | b'[') - ) -} +use distributed::Aggregate; pub fn rejected(err: impl std::fmt::Display) -> HandlerError { HandlerError::Rejected(err.to_string()) } -pub fn read_model_error(e: impl std::fmt::Display) -> HandlerError { - HandlerError::Other(Box::new(std::io::Error::other(e.to_string()))) -} - /// Authenticated user from session (`x-user-id` via DevHeaders or OIDC claim map). pub fn require_user(session: &Session) -> Result { session diff --git a/tests/e2e-celld/crates/identity-service/src/routes.rs b/tests/e2e-celld/crates/identity-service/src/routes.rs index ffac8be19..a39d9748a 100644 --- a/tests/e2e-celld/crates/identity-service/src/routes.rs +++ b/tests/e2e-celld/crates/identity-service/src/routes.rs @@ -1,14 +1,14 @@ -//! Zitadel ingress/scrape commands + AuthUsers projector. +//! Zitadel ingress/scrape commands + the AuthUsers projection. //! -//! No aggregate: the commands publish provider messages, which commit with -//! their ledger receipts. +//! No aggregate: the commands publish user profiles as external facts, which +//! commit with their ledger receipts; the `AUTH_USERS` projection writes them. +use distributed::graphql::SurfaceProjector; use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Routes}; use distributed::AggregateRepository; use crate::bounds::{EventStore, ReadStore}; use crate::deps::AuthDeps; -use crate::handlers::events::project_auth_user; use crate::handlers::ingestors::{zitadel, zitadel_scrape}; pub const MODULE_ID: &str = "identity"; @@ -16,7 +16,11 @@ pub const MODULE_ID: &str = "identity"; /// Prefix of this module's command names (they are named for the provider). pub const COMMAND_PREFIX: &str = "zitadel."; -pub fn routes(repo: R, read_models: S) -> Routes> +pub fn routes( + repo: R, + read_models: S, + auth_projector: SurfaceProjector, +) -> Routes> where R: EventStore, S: ReadStore, @@ -29,6 +33,5 @@ where .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) .handle(scrape) - .events(project_auth_user::EVENTS) - .guarded(project_auth_user::guard, project_auth_user::handle) + .consume_projection(auth_projector) } diff --git a/tests/e2e-ui/crates/projections/src/auth_users.rs b/tests/e2e-ui/crates/projections/src/auth_users.rs index 9dc63d924..2d8caaa93 100644 --- a/tests/e2e-ui/crates/projections/src/auth_users.rs +++ b/tests/e2e-ui/crates/projections/src/auth_users.rs @@ -1,114 +1,156 @@ -//! Zitadel integration-event projection into the AuthUsers query model. +//! Auth users: the Zitadel profile fact + its projection into `auth_users`. +use distributed::mutation_file; +use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; +use distributed::Mutation; use e2e_readmodels::AuthUsers; use serde::{Deserialize, Serialize}; -/// Provider envelope published by `zitadel.ingress.v1`. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ZitadelUserPayload { - pub schema_version: u32, - pub source: String, - pub delivery_id: String, - pub provider: String, - pub provider_subject: String, +/// One Zitadel user's profile as the identity ingestor last saw it. +/// +/// An external fact: the ingestor publishes it with +/// `publish_external`, identified by the provider delivery it came from, and +/// [`AUTH_USERS`] writes it to `auth_users` as it is (the row is the profile). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, distributed::DomainEvent)] +#[domain_event(name = "zitadel.user_profile", version = 1)] +pub struct ZitadelUserProfile { + /// Zitadel subject (OIDC `sub`, session `x-user-id`). + pub user_id: String, + pub email: String, + pub display_name: String, + /// `human` | `machine` pub user_kind: String, - pub emails: Vec, - pub display_name: Option, + /// `pending` | `approved` | `rejected` pub approval_status: String, - pub ingested_at: String, + /// `active` | `deactivated` + pub status: String, + /// When the ingestor saw it (ms since the epoch); not part of the profile. + pub updated_at: String, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ZitadelEmail { - pub address: String, - pub primary: bool, - pub verified: bool, +impl ZitadelUserProfile { + /// Whether this profile differs from the `stored` row (or there is none). + /// `updated_at` is when a profile was seen, not part of it. + pub fn differs_from(&self, stored: Option<&AuthUsers>) -> bool { + stored.is_none_or(|stored| { + ( + &stored.user_id, + &stored.email, + &stored.display_name, + &stored.user_kind, + &stored.approval_status, + &stored.status, + ) != ( + &self.user_id, + &self.email, + &self.display_name, + &self.user_kind, + &self.approval_status, + &self.status, + ) + }) + } } -/// Map a created/updated provider event into an upsert row. -pub fn map_zitadel_user_upsert(event_name: &str, payload: &ZitadelUserPayload) -> AuthUsers { - let email = payload - .emails - .iter() - .find(|email| email.primary) - .or_else(|| payload.emails.first()) - .map(|email| email.address.clone()) - .unwrap_or_default(); - let display_name = payload - .display_name - .clone() - .filter(|name| !name.trim().is_empty()) - .unwrap_or_else(|| { - if email.is_empty() { - payload.provider_subject.clone() - } else { - email.clone() - } - }); - let status = if event_name.contains("deactivated") { - "deactivated".into() - } else { - "active".into() - }; - AuthUsers { - user_id: payload.provider_subject.clone(), - email, - display_name, - user_kind: payload.user_kind.clone(), - approval_status: payload.approval_status.clone(), - status, - updated_at: payload.ingested_at.clone(), - } +/// Mutation: complete-row upsert of an auth user. +/// +/// The constructor name matches the document operation: `mutation SaveAuthUser`. +#[allow(non_snake_case)] +pub fn SaveAuthUser() -> Mutation<()> { + mutation_file!("src/mutations/save_auth_user.mutation.graphql") } -/// Map a deactivate/reactivate provider event into its current user row. -pub fn map_zitadel_user_status(event_name: &str, payload: &ZitadelUserPayload) -> AuthUsers { - let mut row = map_zitadel_user_upsert(event_name, payload); - if event_name.contains("reactivated") { - row.status = "active".into(); - } else if event_name.contains("deactivated") { - row.status = "deactivated".into(); - } - row +distributed::projection! { + pub const AUTH_USERS: ProjectionDescriptor = { + name: "project_auth_users", + version: 1, + epoch: "e2e-ui-auth-users-v1", + model: AuthUsers, + on { + events: [ZitadelUserProfile], + mutation: SaveAuthUser, + input: { user: body }, + }, + }; } #[cfg(test)] mod tests { + use distributed::{DomainEventOccurrence, ExternalEventSource, RowValue, TableMutation}; + use super::*; - fn payload() -> ZitadelUserPayload { - ZitadelUserPayload { - schema_version: 1, - source: "zitadel".into(), - delivery_id: "d1".into(), - provider: "zitadel".into(), - provider_subject: "user-99".into(), + fn ada() -> ZitadelUserProfile { + ZitadelUserProfile { + user_id: "user-99".into(), + email: "ada@example.com".into(), + display_name: "Ada".into(), user_kind: "human".into(), - emails: vec![ZitadelEmail { - address: "ada@example.com".into(), - primary: true, - verified: true, - }], - display_name: Some("Ada".into()), approval_status: "pending".into(), - ingested_at: "2026-01-01T00:00:00Z".into(), + status: "deactivated".into(), + updated_at: "1".into(), } } #[test] - fn created_maps_active_user() { - let row = map_zitadel_user_upsert("zitadel.user.human.created.v1", &payload()); - assert_eq!(row.user_id, "user-99"); - assert_eq!(row.email, "ada@example.com"); - assert_eq!(row.display_name, "Ada"); - assert_eq!(row.status, "active"); - assert_eq!(row.approval_status, "pending"); + fn a_profile_upserts_its_row() { + let occurrence = DomainEventOccurrence::capture_external( + ExternalEventSource { + producer: "zitadel.ingress.v1".into(), + stream: "delivery-1".into(), + position: 1, + key: "user-99".into(), + }, + std::time::SystemTime::UNIX_EPOCH, + Default::default(), + &ada(), + ) + .unwrap(); + let lowered = AUTH_USERS + .server_executor() + .unwrap() + .plan(&occurrence) + .unwrap(); + let TableMutation::UpsertRow(row) = &lowered.write_plan.mutations[0] else { + panic!("expected upsert"); + }; + for (column, value) in [ + ("user_id", "user-99"), + ("display_name", "Ada"), + ("status", "deactivated"), + ("approval_status", "pending"), + ] { + assert_eq!( + row.values.get(column), + Some(&RowValue::String(value.into())), + "{column}" + ); + } } #[test] - fn deactivated_sets_status() { - let row = map_zitadel_user_status("zitadel.user.human.deactivated.v1", &payload()); - assert_eq!(row.status, "deactivated"); - assert_eq!(row.user_id, "user-99"); + fn only_a_changed_profile_differs() { + let profile = ada(); + let row = AuthUsers { + user_id: profile.user_id.clone(), + email: profile.email.clone(), + display_name: profile.display_name.clone(), + user_kind: profile.user_kind.clone(), + approval_status: profile.approval_status.clone(), + status: profile.status.clone(), + updated_at: "0".into(), + }; + assert!(profile.differs_from(None)); + assert!(!profile.differs_from(Some(&row)), "only updated_at differs"); + let renamed = AuthUsers { + display_name: "Ada L.".into(), + ..row.clone() + }; + assert!(profile.differs_from(Some(&renamed))); + let active = AuthUsers { + status: "active".into(), + ..row + }; + assert!(profile.differs_from(Some(&active))); } } diff --git a/tests/e2e-ui/crates/projections/src/lib.rs b/tests/e2e-ui/crates/projections/src/lib.rs index 33228112a..92496c9c2 100644 --- a/tests/e2e-ui/crates/projections/src/lib.rs +++ b/tests/e2e-ui/crates/projections/src/lib.rs @@ -5,9 +5,7 @@ mod blob; mod chat; mod todos; -pub use auth_users::{ - map_zitadel_user_status, map_zitadel_user_upsert, ZitadelEmail, ZitadelUserPayload, -}; +pub use auth_users::{SaveAuthUser, ZitadelUserProfile, AUTH_USERS}; pub use blob::{SaveBlobGame, BLOB_GAMES}; pub use chat::{SaveChatMessage, CHAT_MESSAGES}; pub use todos::{DeleteTodo, SaveTodo, TODOS}; diff --git a/tests/e2e-ui/crates/projections/src/mutations/save_auth_user.mutation.graphql b/tests/e2e-ui/crates/projections/src/mutations/save_auth_user.mutation.graphql new file mode 100644 index 000000000..b34f14f1d --- /dev/null +++ b/tests/e2e-ui/crates/projections/src/mutations/save_auth_user.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR. +# Not a public GraphQL schema field. +mutation SaveAuthUser { + upsert_auth_users(object: $input.user) +} diff --git a/tests/e2e-ui/crates/service/src/deps.rs b/tests/e2e-ui/crates/service/src/deps.rs index a4044ec23..f1206c57b 100644 --- a/tests/e2e-ui/crates/service/src/deps.rs +++ b/tests/e2e-ui/crates/service/src/deps.rs @@ -1,5 +1,5 @@ use distributed::microsvc::RepoReadModelDependencies; use distributed::AggregateRepository; -/// Zitadel ingress/scrape + auth_users projector: stores, no aggregate. +/// Zitadel ingress/scrape + the auth_users projection: stores, no aggregate. pub type AuthDeps = RepoReadModelDependencies, S>; diff --git a/tests/e2e-ui/crates/service/src/handlers/events/mod.rs b/tests/e2e-ui/crates/service/src/handlers/events/mod.rs index b29d06595..28f3be14c 100644 --- a/tests/e2e-ui/crates/service/src/handlers/events/mod.rs +++ b/tests/e2e-ui/crates/service/src/handlers/events/mod.rs @@ -1,3 +1,2 @@ -pub mod project_auth_user; pub mod project_chat_messages; pub mod project_todos; diff --git a/tests/e2e-ui/crates/service/src/handlers/events/project_auth_user.rs b/tests/e2e-ui/crates/service/src/handlers/events/project_auth_user.rs deleted file mode 100644 index 3202f046c..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/events/project_auth_user.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! Project `zitadel.user.*.v1` → `auth_users` (join target for chat + blob games). - -use distributed::microsvc::{Context, HandlerError}; -use distributed::read_model::ReadModelWritePlanBuilder; -use e2e_projections::{map_zitadel_user_status, map_zitadel_user_upsert, ZitadelUserPayload}; -use serde_json::{json, Value}; - -use crate::deps::AuthDeps; -use crate::handlers::util::{decode_payload, read_model_error}; - -pub const EVENTS: &[&str] = &[ - "zitadel.user.human.created.v1", - "zitadel.user.human.updated.v1", - "zitadel.user.human.deactivated.v1", - "zitadel.user.human.reactivated.v1", - "zitadel.user.machine.created.v1", -]; - -pub fn guard(_ctx: &Context>) -> bool -where - R: crate::bounds::EventStore, - S: crate::bounds::ReadStore, -{ - true -} - -pub async fn handle(ctx: &Context<'_, AuthDeps>) -> Result -where - R: crate::bounds::EventStore, - S: crate::bounds::ReadStore, -{ - let payload: ZitadelUserPayload = decode_payload(ctx.message())?; - let name = ctx.message().name(); - let row = if name.contains("deactivated") || name.contains("reactivated") { - map_zitadel_user_status(name, &payload) - } else { - map_zitadel_user_upsert(name, &payload) - }; - - let store = ctx.read_model_store(); - let mut plan = ReadModelWritePlanBuilder::new(); - plan.upsert(&row).map_err(read_model_error)?; - plan.commit(store).await.map_err(read_model_error)?; - - Ok(json!({ - "event": name, - "user_id": row.user_id, - "status": row.status, - "display_name": row.display_name, - })) -} diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/auth.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/auth.rs index 023fb7729..67f292a86 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/auth.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/auth.rs @@ -6,13 +6,14 @@ use std::env; +use axum::http::HeaderMap; use distributed::command_dispatch::VerifiedPrincipal; use distributed::microsvc::{HandlerError, Session, ROLE_KEY, USER_ID_KEY}; /// Env var for the shared secret (required for fixture/curl path). pub const SECRET_ENV: &str = "ZITADEL_INGESTOR_SECRET"; -/// Preferred Action/HTTP header (lowercase session keys). +/// Preferred Action/HTTP header. pub const SECRET_HEADER: &str = "x-zitadel-ingestor-secret"; /// When `1`/`true`, accept native Actions v2 event envelopes without shared secret. @@ -54,11 +55,12 @@ pub fn allow_action_events() -> bool { ) } -pub fn presented_secret(session: &Session) -> Option { - if let Some(v) = session.get(SECRET_HEADER).filter(|s| !s.is_empty()) { +pub fn presented_secret(headers: &HeaderMap) -> Option { + let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()); + if let Some(v) = header(SECRET_HEADER).filter(|s| !s.is_empty()) { return Some(v.to_string()); } - if let Some(auth) = session.get("authorization") { + if let Some(auth) = header("authorization") { if let Some(token) = auth .strip_prefix("Bearer ") .or_else(|| auth.strip_prefix("bearer ")) @@ -72,8 +74,11 @@ pub fn presented_secret(session: &Session) -> Option { None } -pub fn verify_authenticity(session: &Session, is_action_event: bool) -> Result<(), HandlerError> { - if let Some(presented) = presented_secret(session) { +/// Whether the request with `headers` may run an ingestor command: it +/// presents the configured secret, or it is an Actions v2 event body +/// (`is_action_event`) and those are allowed. +pub fn verify_authenticity(headers: &HeaderMap, is_action_event: bool) -> Result<(), HandlerError> { + if let Some(presented) = presented_secret(headers) { let expected = configured_secret().ok_or_else(|| { HandlerError::Unauthorized(format!( "{SECRET_ENV} is not configured; refusing Zitadel ingress" @@ -110,7 +115,6 @@ pub fn verify_authenticity(session: &Session, is_action_event: bool) -> Result<( #[cfg(test)] pub(super) mod tests { use super::*; - use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; static ENV_LOCK: Mutex<()> = Mutex::new(()); @@ -161,18 +165,18 @@ pub(super) mod tests { f(); } - fn session(pairs: &[(&str, &str)]) -> Session { - let mut m = HashMap::new(); - for (k, v) in pairs { - m.insert((*k).to_string(), (*v).to_string()); + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert(*name, value.parse().unwrap()); } - Session::from_map(m) + headers } #[test] fn rejects_when_secret_not_configured() { with_env(None, false, || { - let err = verify_authenticity(&session(&[(SECRET_HEADER, "x")]), false).unwrap_err(); + let err = verify_authenticity(&headers(&[(SECRET_HEADER, "x")]), false).unwrap_err(); assert!(matches!(err, HandlerError::Unauthorized(_))); }); } @@ -180,14 +184,26 @@ pub(super) mod tests { #[test] fn accepts_matching_header() { with_env(Some("s3cret"), false, || { - verify_authenticity(&session(&[(SECRET_HEADER, "s3cret")]), false).unwrap(); + verify_authenticity(&headers(&[(SECRET_HEADER, "s3cret")]), false).unwrap(); }); } #[test] fn accepts_action_event_when_allowed() { with_env(None, true, || { - verify_authenticity(&Session::new(), true).unwrap(); + verify_authenticity(&HeaderMap::new(), true).unwrap(); + }); + } + + #[test] + fn accepts_matching_bearer_and_rejects_a_wrong_secret() { + with_env(Some("s3cret"), true, || { + verify_authenticity(&headers(&[("authorization", "Bearer s3cret")]), false).unwrap(); + // A wrong secret is refused even for an allowed Action event body. + let err = verify_authenticity(&headers(&[(SECRET_HEADER, "nope")]), true).unwrap_err(); + assert!(matches!(err, HandlerError::Unauthorized(_))); + let err = verify_authenticity(&HeaderMap::new(), false).unwrap_err(); + assert!(matches!(err, HandlerError::Unauthorized(_))); }); } } diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/handle.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/handle.rs index 7549b096f..0502dc6ed 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/handle.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/handle.rs @@ -1,12 +1,14 @@ -//! Command: `zitadel.ingress.v1` — map one provider delivery and publish its -//! provider message. No aggregate: the message commits with the command's -//! ledger receipt. +//! Command: `zitadel.ingress.v1` — map one provider delivery and publish the +//! user's profile. No aggregate: the profile is an external fact, committed +//! with the command's ledger receipt and projected into `auth_users`. +use axum::http::HeaderMap; use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use distributed::command_dispatch::deterministic_command_id; use distributed::microsvc::{ - CausalCommandContext, CausalDispatchError, HandlerError, Service, Session, + CausalCommandContext, CausalDispatchError, HandlerError, HttpCommandDispatch, }; +use distributed::ExternalEventSource; use serde::Serialize; use serde_json::Value; @@ -14,14 +16,14 @@ use super::auth::{ingestor_principal, ingestor_session, verify_authenticity, ING use super::map::{ looks_like_action_event, map_action_delivery, normalize_ingress_body, ZitadelIngressInput, }; -use super::publish::provider_message; /// Command name, and the path of its HTTP edge (POST `/{COMMAND}`). pub const COMMAND: &str = "zitadel.ingress.v1"; #[derive(Debug, Serialize, distributed::CommandOutput)] pub struct ZitadelIngressPayload { - /// Provider message published; `None` when the event type maps to none. + /// Provider event the delivery was; `None` when the event type maps to + /// none, and nothing was published. pub published: Option, /// Why nothing was published. pub skipped: Option, @@ -53,20 +55,26 @@ pub async fn handle( .map_err(|error| HandlerError::Other(Box::new(error))); }; - // Provider envelope only — the projector maps it to auth_users. - let command_id = ctx.message_id().unwrap_or_default(); - let message = provider_message(format!("{COMMAND}:{command_id}"), &mapped)?; - ctx.outbox(message) + // The profile is identified by this command: a redelivery is this + // command again, and another command never publishes the same fact. + let source = ExternalEventSource { + producer: COMMAND.into(), + stream: ctx.message_id().unwrap_or_default().into(), + position: 1, + key: mapped.profile.user_id.clone(), + }; + let payload = ZitadelIngressPayload { + published: Some(mapped.message_name), + skipped: None, + event_type: input.event_type, + event_id: Some(mapped.delivery_id), + provider_subject: Some(mapped.profile.user_id.clone()), + user_kind: Some(mapped.profile.user_kind.clone()), + approval_status: Some(mapped.profile.approval_status.clone()), + }; + ctx.publish_external(source, mapped.profile) .commit()? - .succeeded(ZitadelIngressPayload { - published: Some(mapped.message_name), - skipped: None, - event_type: input.event_type, - event_id: Some(mapped.delivery_id), - provider_subject: Some(mapped.payload.provider_subject), - user_kind: Some(mapped.payload.user_kind), - approval_status: Some(mapped.payload.approval_status), - }) + .succeeded(payload) } /// The ledger command id of one delivery. Zitadel delivers an event again @@ -86,15 +94,14 @@ pub fn ingress_command_id(input: &ZitadelIngressInput) -> String { } } -/// HTTP edge of [`COMMAND`]: authenticate the caller, then dispatch the -/// delivery as the ingestor. `caller` is the request's headers; none of them +/// HTTP edge of [`COMMAND`] (`Service::with_http_command`): authenticate the +/// caller, then dispatch the delivery as the ingestor. No request header /// reaches the command. -pub async fn receive( - service: &Service, - caller: &Session, +pub fn http_edge( + headers: &HeaderMap, body: Value, -) -> Result { - verify_authenticity(caller, looks_like_action_event(&body)) +) -> Result { + verify_authenticity(headers, looks_like_action_event(&body)) .map_err(CausalDispatchError::Handler)?; if body.is_null() { return Err(CausalDispatchError::BadRequest( @@ -105,52 +112,67 @@ pub async fn receive( let command_id = ingress_command_id(&input); let input = serde_json::to_value(input) .map_err(|error| CausalDispatchError::Internal(error.to_string()))?; - service - .dispatch_causal( - COMMAND, - &command_id, - input, - ingestor_session(), - ingestor_principal(), - ) - .await + Ok(HttpCommandDispatch { + command_id, + input, + session: ingestor_session(), + principal: ingestor_principal(), + }) } #[cfg(test)] mod tests { + use std::sync::Arc; + use super::super::auth::tests::IngestorEnv; use super::super::auth::SECRET_HEADER; - use super::super::map::HUMAN_CREATED; use super::*; - use distributed::microsvc::Routes; + use distributed::microsvc::{self, Routes, Service}; use distributed::{InMemoryRepository, OutboxStore}; + use e2e_projections::ZitadelUserProfile; use serde_json::json; - fn caller(secret: &str) -> Session { - let mut caller = Session::new(); - caller.set(SECRET_HEADER, secret); - caller - } - - async fn provider_messages(repo: &InMemoryRepository) -> usize { + /// The `zitadel.user_profile` facts in the outbox. + async fn published_profiles(repo: &InMemoryRepository) -> Vec { repo.outbox_store() .pending(usize::MAX) .await .unwrap() .iter() - .filter(|message| message.event_type == HUMAN_CREATED) - .count() + .filter_map(|message| message.domain_event_occurrence().ok()) + .map(|occurrence| occurrence.decode_body().unwrap()) + .collect() + } + + async fn post(base: &str, secret: &str, body: &Value) -> (u16, Value) { + let response = reqwest::Client::new() + .post(format!("{base}/{COMMAND}")) + .header(SECRET_HEADER, secret) + // A caller-chosen identity never reaches the command. + .header("x-user-id", "attacker") + .json(body) + .send() + .await + .unwrap(); + (response.status().as_u16(), response.json().await.unwrap()) } #[tokio::test] - async fn a_redelivered_webhook_publishes_one_provider_message() { + async fn a_redelivered_webhook_publishes_one_profile() { let _env = IngestorEnv::set(Some("s3cret"), false); let repo = InMemoryRepository::new(); - let service = Service::new().named("identity").routes( - Routes::for_stores(repo.clone(), repo.clone()) - .typed_command(command()) - .handle(handle), - ); + let service = Service::new() + .named("identity") + .routes( + Routes::for_stores(repo.clone(), repo.clone()) + .typed_command(command()) + .handle(handle), + ) + .with_http_command(COMMAND, http_edge); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let app = microsvc::router(Arc::new(service)); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let delivery = json!({ "event_id": "evt-1", "event_type": "user.human.created", @@ -160,29 +182,24 @@ mod tests { }); // A caller without the secret runs no command. - let refused = receive(&service, &caller("wrong"), delivery.clone()).await; - assert!( - matches!( - refused, - Err(CausalDispatchError::Handler(HandlerError::Unauthorized(_))) - ), - "{refused:?}" - ); - assert_eq!(provider_messages(&repo).await, 0); - - let first = receive(&service, &caller("s3cret"), delivery.clone()) - .await - .unwrap(); - assert_eq!(first["published"], HUMAN_CREATED); - assert_eq!(first["event_id"], "evt-1"); - assert_eq!(provider_messages(&repo).await, 1); + let (status, refused) = post(&base, "wrong", &delivery).await; + assert_eq!(status, 401, "{refused}"); + assert!(published_profiles(&repo).await.is_empty()); + + let (status, first) = post(&base, "s3cret", &delivery).await; + assert_eq!(status, 200, "{first}"); + assert_eq!(first["payload"]["published"], super::super::HUMAN_CREATED); + assert_eq!(first["payload"]["event_id"], "evt-1"); + let profiles = published_profiles(&repo).await; + assert_eq!(profiles.len(), 1); + assert_eq!(profiles[0].user_id, "sub-1"); + assert_eq!(profiles[0].display_name, "Ada"); + assert_eq!(profiles[0].status, "active"); // The provider delivers the event again: the stored receipt answers. - let again = receive(&service, &caller("s3cret"), delivery) - .await - .unwrap(); + let (_, again) = post(&base, "s3cret", &delivery).await; assert_eq!(again, first); - assert_eq!(provider_messages(&repo).await, 1); + assert_eq!(published_profiles(&repo).await.len(), 1); // One delivery id for another event is refused, not published. let other = json!({ @@ -190,11 +207,8 @@ mod tests { "event_type": "user.human.created", "user_id": "sub-2", }); - let reused = receive(&service, &caller("s3cret"), other).await; - assert!( - matches!(reused, Err(CausalDispatchError::CommandIdReuse)), - "{reused:?}" - ); - assert_eq!(provider_messages(&repo).await, 1); + let (status, reused) = post(&base, "s3cret", &other).await; + assert_eq!(status, 409, "{reused}"); + assert_eq!(published_profiles(&repo).await.len(), 1); } } diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/map.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/map.rs index 5e351e733..acf52bb8c 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/map.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/map.rs @@ -1,6 +1,7 @@ -//! Map Zitadel Action / fixture payloads → provider bus subjects + envelopes. +//! Map Zitadel Action / fixture payloads → the provider event they name and +//! the user profile they carry. -use e2e_projections::{ZitadelEmail, ZitadelUserPayload}; +use e2e_projections::ZitadelUserProfile; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -38,11 +39,49 @@ pub struct ZitadelIngressEmail { pub verified: Option, } +/// One provider delivery: which Zitadel event it is, and the user's profile +/// after it. #[derive(Debug, Clone)] pub struct MappedDelivery { pub message_name: String, pub delivery_id: String, - pub payload: ZitadelUserPayload, + pub profile: ZitadelUserProfile, +} + +/// The profile a provider event leaves a user with. A deactivation leaves +/// them `deactivated`, every other event `active`; an empty display name +/// falls back to the email, then the subject. +pub fn user_profile( + message_name: &str, + user_id: &str, + user_kind: String, + email: String, + display_name: Option, + approval_status: String, +) -> ZitadelUserProfile { + let display_name = display_name + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| { + if email.is_empty() { + user_id.to_string() + } else { + email.clone() + } + }); + let status = if message_name == HUMAN_DEACTIVATED { + "deactivated" + } else { + "active" + }; + ZitadelUserProfile { + user_id: user_id.to_string(), + email, + display_name, + user_kind, + approval_status, + status: status.into(), + updated_at: now_ms(), + } } pub fn looks_like_action_event(raw: &Value) -> bool { @@ -203,26 +242,20 @@ pub fn map_action_delivery(input: &ZitadelIngressInput) -> Option) -> Option<&'s None } -fn normalize_emails(input: &ZitadelIngressInput) -> Vec { - if let Some(list) = &input.emails { - if !list.is_empty() { - return list - .iter() - .map(|e| ZitadelEmail { - address: e.address.clone(), - primary: e.primary.unwrap_or(false), - verified: e.verified.unwrap_or(true), - }) - .collect(); - } - } - if let Some(email) = input.email.as_ref().filter(|s| !s.trim().is_empty()) { - return vec![ZitadelEmail { - address: email.clone(), - primary: true, - verified: true, - }]; +/// The delivery's primary email (the first listed when none is marked), or +/// its single `email`; empty when it has none. +fn primary_email(input: &ZitadelIngressInput) -> String { + let listed = input.emails.iter().flatten(); + if let Some(email) = listed + .clone() + .find(|email| email.primary == Some(true)) + .or_else(|| listed.clone().next()) + { + return email.address.clone(); } - Vec::new() + input + .email + .clone() + .filter(|email| !email.trim().is_empty()) + .unwrap_or_default() } fn derive_approval(input: &ZitadelIngressInput, user_kind: &str) -> String { @@ -325,12 +353,12 @@ fn derive_approval(input: &ZitadelIngressInput, user_kind: &str) -> String { } } -fn now_rfc3339ish() -> String { +/// Milliseconds since the epoch: a sortable timestamp without chrono. +fn now_ms() -> String { use std::time::{SystemTime, UNIX_EPOCH}; let d = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default(); - // Sortable timestamp without chrono dependency. format!("{}", d.as_millis()) } @@ -356,9 +384,11 @@ mod tests { let m = map_action_delivery(&input).expect("mapped"); assert_eq!(m.message_name, HUMAN_CREATED); assert_eq!(m.delivery_id, "d1"); - assert_eq!(m.payload.approval_status, "pending"); - assert_eq!(m.payload.user_kind, "human"); - assert_eq!(m.payload.emails[0].address, "ada@example.com"); + assert_eq!(m.profile.approval_status, "pending"); + assert_eq!(m.profile.user_kind, "human"); + assert_eq!(m.profile.email, "ada@example.com"); + assert_eq!(m.profile.display_name, "Ada"); + assert_eq!(m.profile.status, "active"); } #[test] @@ -377,7 +407,7 @@ mod tests { }; let m = map_action_delivery(&input).unwrap(); assert_eq!(m.message_name, HUMAN_UPDATED); - assert_eq!(m.payload.approval_status, "approved"); + assert_eq!(m.profile.approval_status, "approved"); } #[test] @@ -414,6 +444,47 @@ mod tests { assert_eq!(d.provider_subject.as_deref(), Some("user-99")); let m = map_action_delivery(&d).expect("mapped"); assert_eq!(m.message_name, HUMAN_CREATED); - assert_eq!(m.payload.provider_subject, "user-99"); + assert_eq!(m.profile.user_id, "user-99"); + } + + #[test] + fn a_deactivation_leaves_the_user_deactivated_and_names_fall_back() { + let input = ZitadelIngressInput { + delivery_id: Some("d4".into()), + event_type: Some("user.human.deactivated".into()), + provider_subject: Some("sub-1".into()), + user_kind: None, + email: None, + emails: Some(vec![ + ZitadelIngressEmail { + address: "old@example.com".into(), + primary: None, + verified: None, + }, + ZitadelIngressEmail { + address: "ada@example.com".into(), + primary: Some(true), + verified: None, + }, + ]), + display_name: Some(" ".into()), + approval_status: None, + grants: None, + roles: None, + }; + let m = map_action_delivery(&input).unwrap(); + assert_eq!(m.message_name, HUMAN_DEACTIVATED); + assert_eq!(m.profile.status, "deactivated"); + assert_eq!(m.profile.email, "ada@example.com"); + assert_eq!(m.profile.display_name, "ada@example.com"); + + let reactivated = map_action_delivery(&ZitadelIngressInput { + event_type: Some("user.human.reactivated".into()), + emails: None, + ..input + }) + .unwrap(); + assert_eq!(reactivated.profile.status, "active"); + assert_eq!(reactivated.profile.display_name, "sub-1"); } } diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/mod.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/mod.rs index b60eeb03f..ad61970af 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/mod.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/mod.rs @@ -1,12 +1,14 @@ -//! Zitadel Action/HTTP ingress + Management API scrape → provider messages only. +//! Zitadel Action/HTTP ingress + Management API scrape → user profiles. //! //! Teaching fixture (simplified from gitkb domain-service): -//! 1. Authenticity (`auth`) — shared secret header, checked at the HTTP edge; -//! it vouches for the ingestor identity the commands run as -//! 2. Map (`map`) — Action payload → typed `zitadel.*.v1` subjects -//! 3. Publish (`publish`) — outbox provider message, committed with the -//! command's ledger receipt (no aggregate) -//! 4. Projector (`project_auth_user`) — upserts `auth_users` for GraphQL joins +//! 1. Authenticity (`auth`) — shared secret header, checked by the command's +//! HTTP edge; it vouches for the ingestor identity the commands run as +//! 2. Map (`map`) — Action payload → the `zitadel.*.v1` event it is and the +//! user's [`ZitadelUserProfile`](e2e_projections::ZitadelUserProfile) +//! 3. Publish — `publish_external`: the profile as an external fact, +//! committed with the command's ledger receipt (no aggregate) +//! 4. Projection (`e2e_projections::AUTH_USERS`) — upserts `auth_users` for +//! GraphQL joins //! 5. Scrape (`scrape`) — periodic Management API reconcile for missed events //! //! See `docs/zitadel-ingestor.md`. @@ -14,7 +16,6 @@ mod auth; mod handle; mod map; -mod publish; pub mod scrape; pub use auth::{ @@ -22,36 +23,12 @@ pub use auth::{ verify_authenticity, ALLOW_ACTION_EVENTS_ENV, INGESTOR_ROLE, INGESTOR_USER_ID, SECRET_ENV, SECRET_HEADER, }; -pub use handle::{command, handle, ingress_command_id, receive, ZitadelIngressPayload, COMMAND}; +pub use handle::{command, handle, http_edge, ingress_command_id, ZitadelIngressPayload, COMMAND}; pub use map::{ - looks_like_action_event, map_action_delivery, normalize_ingress_body, MappedDelivery, - ZitadelIngressEmail, ZitadelIngressInput, HUMAN_CREATED, HUMAN_DEACTIVATED, HUMAN_REACTIVATED, - HUMAN_UPDATED, MACHINE_CREATED, + looks_like_action_event, map_action_delivery, normalize_ingress_body, user_profile, + MappedDelivery, ZitadelIngressEmail, ZitadelIngressInput, HUMAN_CREATED, HUMAN_DEACTIVATED, + HUMAN_REACTIVATED, HUMAN_UPDATED, MACHINE_CREATED, }; -pub use publish::provider_message; pub use scrape::{ spawn_scrape_loop, ZitadelScrapeConfig, API_URL_ENV, INTERVAL_ENV, ON_START_ENV, TOKEN_ENV, }; - -/// Provider event names published by this ingestor (never domain forgeries). -pub fn is_provider_message_name(name: &str) -> bool { - name.starts_with("zitadel.") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn provider_names_are_zitadel_prefixed() { - for name in [ - HUMAN_CREATED, - HUMAN_UPDATED, - HUMAN_DEACTIVATED, - HUMAN_REACTIVATED, - MACHINE_CREATED, - ] { - assert!(is_provider_message_name(name), "{name}"); - } - } -} diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/publish.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/publish.rs deleted file mode 100644 index b87415745..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/publish.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Provider message encoding shared by ingress and scrape. - -use distributed::microsvc::HandlerError; -use distributed::OutboxMessage; - -use super::map::MappedDelivery; - -/// Encode a mapped provider delivery as the outbox message `id`. -/// -/// Callers derive `id` from their command id, so one command never stages an -/// id another command committed. -pub fn provider_message( - id: String, - mapped: &MappedDelivery, -) -> Result { - OutboxMessage::encode(id, mapped.message_name.as_str(), &mapped.payload) - .map_err(|error| HandlerError::Other(Box::new(error))) -} diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/scrape.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/scrape.rs index 38606d7ef..c64105329 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/scrape.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel/scrape.rs @@ -9,14 +9,10 @@ use std::sync::Arc; use std::time::Duration; use distributed::microsvc::Service; -use e2e_projections::{ - map_zitadel_user_status, map_zitadel_user_upsert, ZitadelEmail, ZitadelUserPayload, -}; -use e2e_readmodels::AuthUsers; use serde::Deserialize; use serde_json::{json, Value}; -use super::map::{MappedDelivery, HUMAN_DEACTIVATED, HUMAN_UPDATED, MACHINE_CREATED}; +use super::map::{user_profile, MappedDelivery, HUMAN_DEACTIVATED, HUMAN_UPDATED, MACHINE_CREATED}; /// Env: Management API base (no trailing slash). Falls back to `OIDC_ISSUER`. pub const API_URL_ENV: &str = "ZITADEL_API_URL"; @@ -99,17 +95,6 @@ pub async fn list_mapped_users( )) } -/// The `auth_users` row of a listed user: what the projector writes for the -/// same provider message. -pub fn auth_user_row(mapped: &MappedDelivery) -> AuthUsers { - let name = mapped.message_name.as_str(); - if name.contains("deactivated") || name.contains("reactivated") { - map_zitadel_user_status(name, &mapped.payload) - } else { - map_zitadel_user_upsert(name, &mapped.payload) - } -} - #[derive(Debug, Clone, Deserialize)] struct SearchResponse { #[serde(default)] @@ -161,8 +146,6 @@ struct MgmtProfile { struct MgmtEmail { #[serde(default)] email: Option, - #[serde(default, rename = "isEmailVerified")] - is_email_verified: Option, } #[derive(Debug, Clone, Deserialize)] @@ -291,39 +274,20 @@ fn map_mgmt_user(user: &MgmtUser) -> Option { let fingerprint = simple_fingerprint(&[&email, &display_name, state, &user_kind, &change]); let delivery_id = format!("zitadel-scrape:{id}:{fingerprint}"); - let emails = if email.is_empty() { - Vec::new() - } else { - vec![ZitadelEmail { - address: email, - primary: true, - verified: user - .human - .as_ref() - .and_then(|h| h.email.as_ref()) - .and_then(|e| e.is_email_verified) - .unwrap_or(true), - }] - }; - - let payload = ZitadelUserPayload { - schema_version: 1, - source: "zitadel-scrape".into(), - delivery_id: delivery_id.clone(), - provider: "zitadel".into(), - provider_subject: id.to_string(), + let profile = user_profile( + message_name, + id, user_kind, - emails, - display_name: Some(display_name), + email, + Some(display_name), // Scrape treats every listed identity as a directory member. - approval_status: "approved".into(), - ingested_at: now_ms(), - }; + "approved".into(), + ); Some(MappedDelivery { message_name: message_name.to_string(), delivery_id, - payload, + profile, }) } @@ -341,14 +305,6 @@ fn simple_fingerprint(parts: &[&str]) -> String { format!("{hash:016x}") } -fn now_ms() -> String { - use std::time::{SystemTime, UNIX_EPOCH}; - let d = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - format!("{}", d.as_millis()) -} - /// Background loop: optional immediate scrape, then every `cfg.interval`. /// Each scrape is one `zitadel.scrape.v1` command on `service`. pub fn spawn_scrape_loop(service: Arc, cfg: ZitadelScrapeConfig) { @@ -395,9 +351,10 @@ mod tests { }); let m = map_management_user(&raw).expect("mapped"); assert_eq!(m.message_name, HUMAN_UPDATED); - assert_eq!(m.payload.provider_subject, "user-1"); - assert_eq!(m.payload.display_name.as_deref(), Some("Alice")); - assert_eq!(m.payload.emails[0].address, "alice@e2e.local"); + assert_eq!(m.profile.user_id, "user-1"); + assert_eq!(m.profile.display_name, "Alice"); + assert_eq!(m.profile.email, "alice@e2e.local"); + assert_eq!(m.profile.approval_status, "approved"); assert!(m.delivery_id.starts_with("zitadel-scrape:user-1:")); } @@ -413,6 +370,7 @@ mod tests { }); let m = map_management_user(&raw).unwrap(); assert_eq!(m.message_name, HUMAN_DEACTIVATED); + assert_eq!(m.profile.status, "deactivated"); } #[test] @@ -424,7 +382,7 @@ mod tests { }); let m = map_management_user(&raw).unwrap(); assert_eq!(m.message_name, MACHINE_CREATED); - assert_eq!(m.payload.user_kind, "machine"); + assert_eq!(m.profile.user_kind, "machine"); } #[test] diff --git a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel_scrape.rs b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel_scrape.rs index 3bad30484..88ab18100 100644 --- a/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel_scrape.rs +++ b/tests/e2e-ui/crates/service/src/handlers/ingestors/zitadel_scrape.rs @@ -1,33 +1,30 @@ //! Command: `zitadel.scrape.v1` — reconcile from the Management API. //! -//! Lists every user and publishes the ones whose `auth_users` row differs -//! from the listed profile: one commit holds a provider message and the row -//! per changed user, with the command's receipt. No aggregate. Requires +//! Lists every user and publishes the profiles that differ from their +//! `auth_users` row, in one commit with the command's receipt; the +//! `auth_users` projection writes them. No aggregate. Requires //! `ZITADEL_SERVICE_USER_TOKEN` + `ZITADEL_API_URL` / `OIDC_ISSUER` in env. -use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use std::future::Future; use std::pin::Pin; +use axum::http::HeaderMap; +use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; use distributed::microsvc::{ - CausalCommandContext, CausalDispatchError, HandlerError, PreparedCommandHandler, Service, - Session, + CausalCommandContext, CausalDispatchError, HandlerError, HttpCommandDispatch, + PreparedCommandHandler, Service, }; -use distributed::read_model::ReadModelWritePlanBuilder; use distributed::{ - ReadModelWorkspaceExt, ReadModelWritePlanStore, RelationalReadModelQueryStore, RowKey, RowValue, + ExternalEventSource, ReadModelWorkspaceExt, ReadModelWritePlanStore, + RelationalReadModelQueryStore, RowKey, RowValue, }; use e2e_readmodels::AuthUsers; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use super::zitadel::scrape::{ - auth_user_row, list_mapped_users, ZitadelScrapeConfig, API_URL_ENV, TOKEN_ENV, -}; +use super::zitadel::scrape::{list_mapped_users, ZitadelScrapeConfig, API_URL_ENV, TOKEN_ENV}; use super::zitadel::MappedDelivery; -use super::zitadel::{ - ingestor_principal, ingestor_session, provider_message, verify_authenticity, INGESTOR_ROLE, -}; +use super::zitadel::{ingestor_principal, ingestor_session, verify_authenticity, INGESTOR_ROLE}; pub const COMMAND: &str = "zitadel.scrape.v1"; @@ -41,7 +38,7 @@ pub struct ZitadelScrapeInput { pub struct ZitadelScrapePayload { /// Users the Management API listed. pub listed: u32, - /// Provider messages published: one per user whose profile changed. + /// Profiles published: one per user whose profile changed. pub published: u32, /// Listed users not published: unchanged, or with no usable id. pub skipped: u32, @@ -86,23 +83,10 @@ where } } -/// Whether a listed profile must be published: its row is missing or differs. -/// -/// A scrape commits a user's row with that user's message, so an equal row -/// means the profile was already published. `updated_at` is when a profile was -/// ingested, not part of it. -pub fn profile_changed(listed: &AuthUsers, stored: Option<&AuthUsers>) -> bool { - stored.is_none_or(|stored| { - AuthUsers { - updated_at: listed.updated_at.clone(), - ..stored.clone() - } != *listed - }) -} - -/// Publish the `users` (of `listed`) whose profile changed, each with its -/// `auth_users` row. Directory joins (chat author, blob owner) do not wait for -/// the bus: the row commits here, with the message. +/// Publish the `users` (of `listed`) whose profile differs from their +/// `auth_users` row. A row equal to the listed profile means it was already +/// published and projected; a profile published but not yet projected is +/// published again, and the projection writes the same row twice. async fn reconcile( ctx: &CausalCommandContext<'_, ()>, read_models: &S, @@ -112,41 +96,47 @@ async fn reconcile( where S: ReadModelWritePlanStore + RelationalReadModelQueryStore, { - // Message ids come from this command's id, so a scrape never meets an id - // an earlier one committed. + // Each profile is identified by this command and its place in the + // listing, so a scrape never publishes a fact an earlier one did. let command_id = ctx.message_id().unwrap_or_default(); - let mut messages = Vec::new(); - let mut rows = ReadModelWritePlanBuilder::new(); + let mut changed = Vec::new(); for user in users { - let row = auth_user_row(user); - let key = RowKey::new([("user_id", RowValue::String(row.user_id.clone()))]); + let key = RowKey::new([("user_id", RowValue::String(user.profile.user_id.clone()))]); let stored = read_models .workspace() .load::(key) .one() .await .map_err(|error| HandlerError::Other(Box::new(error)))?; - if !profile_changed(&row, stored.as_ref().map(|stored| &stored.data)) { - continue; + if user + .profile + .differs_from(stored.as_ref().map(|stored| &stored.data)) + { + changed.push(user.profile.clone()); } - let id = format!("{COMMAND}:{command_id}:{}", messages.len()); - messages.push(provider_message(id, user)?); - rows.upsert(&row) - .map_err(|error| HandlerError::Other(Box::new(error)))?; } let payload = ZitadelScrapePayload { listed: listed as u32, - published: messages.len() as u32, - skipped: listed.saturating_sub(messages.len()) as u32, + published: changed.len() as u32, + skipped: listed.saturating_sub(changed.len()) as u32, }; - let mut messages = messages.into_iter(); - let Some(first) = messages.next() else { + let source = + |position: usize, profile: &e2e_projections::ZitadelUserProfile| ExternalEventSource { + producer: COMMAND.into(), + stream: command_id.into(), + position: position as u64 + 1, + key: profile.user_id.clone(), + }; + let mut changed = changed.into_iter().enumerate(); + let Some((position, first)) = changed.next() else { return PreparedCommand::prepare(payload) .map_err(|error| HandlerError::Other(Box::new(error))); }; - messages - .fold(ctx.outbox(first), |unit, message| unit.outbox(message)) - .read_models(rows) + changed + .fold( + ctx.publish_external(source(position, &first), first), + |unit, (position, profile)| unit.publish_external(source(position, &profile), profile), + ) .commit()? .succeeded(payload) } @@ -165,67 +155,45 @@ pub async fn scrape(service: &Service, trigger: &str) -> Result Result { - verify_authenticity(caller, false).map_err(CausalDispatchError::Handler)?; - scrape(service, "http").await +/// HTTP edge of [`COMMAND`] (`Service::with_http_command`): the shared +/// secret, then a scrape as the ingestor with a fresh id, like [`scrape`]. +/// The body is ignored and no request header reaches the command. +pub fn http_edge( + headers: &HeaderMap, + _body: Value, +) -> Result { + verify_authenticity(headers, false).map_err(CausalDispatchError::Handler)?; + Ok(HttpCommandDispatch { + command_id: uuid::Uuid::now_v7().to_string(), + input: json!({ "trigger": "http" }), + session: ingestor_session(), + principal: ingestor_principal(), + }) } #[cfg(test)] mod tests { - use super::super::zitadel::{HUMAN_UPDATED, MACHINE_CREATED}; + use super::super::zitadel::{user_profile, HUMAN_UPDATED}; use super::*; use distributed::microsvc::Routes; use distributed::{InMemoryRepository, OutboxStore}; - use e2e_projections::{ZitadelEmail, ZitadelUserPayload}; + use e2e_projections::{ZitadelUserProfile, AUTH_USERS}; - fn listed_user(subject: &str, display_name: &str, ingested_at: &str) -> MappedDelivery { + fn listed_user(subject: &str, display_name: &str) -> MappedDelivery { MappedDelivery { message_name: HUMAN_UPDATED.into(), delivery_id: format!("zitadel-scrape:{subject}"), - payload: ZitadelUserPayload { - schema_version: 1, - source: "zitadel-scrape".into(), - delivery_id: format!("zitadel-scrape:{subject}"), - provider: "zitadel".into(), - provider_subject: subject.into(), - user_kind: "human".into(), - emails: vec![ZitadelEmail { - address: format!("{subject}@example.com"), - primary: true, - verified: true, - }], - display_name: Some(display_name.into()), - approval_status: "approved".into(), - ingested_at: ingested_at.into(), - }, + profile: user_profile( + HUMAN_UPDATED, + subject, + "human".into(), + format!("{subject}@example.com"), + Some(display_name.into()), + "approved".into(), + ), } } - #[test] - fn a_profile_is_published_when_its_row_is_missing_or_differs() { - let listed = auth_user_row(&listed_user("ada", "Ada", "2")); - assert!(profile_changed(&listed, None)); - - // Only the ingestion time differs: the same profile. - let stored = auth_user_row(&listed_user("ada", "Ada", "1")); - assert!(!profile_changed(&listed, Some(&stored))); - - let renamed = auth_user_row(&listed_user("ada", "Ada L.", "1")); - assert!(profile_changed(&listed, Some(&renamed))); - let deactivated = AuthUsers { - status: "deactivated".into(), - ..stored.clone() - }; - assert!(profile_changed(&listed, Some(&deactivated))); - let pending = AuthUsers { - approval_status: "pending".into(), - ..stored - }; - assert!(profile_changed(&listed, Some(&pending))); - } - /// [`Scrape`] with the listing given, not fetched from Zitadel. struct Listed(InMemoryRepository, Vec); @@ -245,7 +213,7 @@ mod tests { } #[tokio::test] - async fn a_second_scrape_of_an_unchanged_listing_stages_nothing() { + async fn a_scrape_publishes_only_the_profiles_that_differ_from_their_rows() { let repo = InMemoryRepository::new(); let service_listing = |users: Vec| { Service::new().named("identity").routes( @@ -254,39 +222,61 @@ mod tests { .handle(Listed(repo.clone(), users)), ) }; - let staged = || async { + let published = || async { repo.outbox_store() .pending(usize::MAX) .await .unwrap() - .into_iter() - .map(|message| message.event_type) + .iter() + .map(|message| { + let occurrence = message.domain_event_occurrence().unwrap(); + assert_eq!(message.id(), occurrence.id()); + occurrence.decode_body::().unwrap() + }) + .map(|profile| (profile.user_id, profile.display_name)) .collect::>() }; - let users = vec![ - listed_user("ada", "Ada", "1"), - listed_user("grace", "Grace", "1"), - ]; + // Run the `auth_users` projection over everything published. + let project = || async { + for message in repo.outbox_store().pending(usize::MAX).await.unwrap() { + let occurrence = message.domain_event_occurrence().unwrap(); + let lowered = AUTH_USERS + .server_executor() + .unwrap() + .plan(&occurrence) + .unwrap(); + repo.commit_write_plan(lowered.write_plan).await.unwrap(); + } + }; + let users = vec![listed_user("ada", "Ada"), listed_user("grace", "Grace")]; // The listing also held one user with no usable id. let first = scrape(&service_listing(users.clone()), "start") .await .unwrap(); assert_eq!(first, json!({ "listed": 3, "published": 2, "skipped": 1 })); - assert_eq!(staged().await, [HUMAN_UPDATED, HUMAN_UPDATED]); + assert_eq!( + published().await, + [ + ("ada".into(), "Ada".into()), + ("grace".into(), "Grace".into()) + ] + ); + project().await; let unchanged = scrape(&service_listing(users), "interval").await.unwrap(); assert_eq!( unchanged, json!({ "listed": 3, "published": 0, "skipped": 3 }) ); - assert_eq!(staged().await.len(), 2); + assert_eq!(published().await.len(), 2); // One profile changed: that one alone is published. - let mut renamed = listed_user("grace", "Grace H.", "2"); - renamed.message_name = MACHINE_CREATED.into(); let changed = scrape( - &service_listing(vec![listed_user("ada", "Ada", "2"), renamed]), + &service_listing(vec![ + listed_user("ada", "Ada"), + listed_user("grace", "Grace H."), + ]), "interval", ) .await @@ -295,9 +285,6 @@ mod tests { changed, json!({ "listed": 3, "published": 1, "skipped": 2 }) ); - assert_eq!( - staged().await, - [HUMAN_UPDATED, HUMAN_UPDATED, MACHINE_CREATED] - ); + assert_eq!(published().await[2], ("grace".into(), "Grace H.".into())); } } diff --git a/tests/e2e-ui/crates/service/src/handlers/mod.rs b/tests/e2e-ui/crates/service/src/handlers/mod.rs index 024f6087a..fae5fbddb 100644 --- a/tests/e2e-ui/crates/service/src/handlers/mod.rs +++ b/tests/e2e-ui/crates/service/src/handlers/mod.rs @@ -1,4 +1,3 @@ pub mod commands; pub mod events; pub mod ingestors; -pub mod util; diff --git a/tests/e2e-ui/crates/service/src/handlers/util.rs b/tests/e2e-ui/crates/service/src/handlers/util.rs deleted file mode 100644 index adb88a598..000000000 --- a/tests/e2e-ui/crates/service/src/handlers/util.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! Shared event-handler helpers. - -use distributed::bus::Message; -use distributed::microsvc::HandlerError; -use distributed::{BitcodePayloadCodec, PayloadCodec}; -use serde::de::DeserializeOwned; - -/// Decode event payload as JSON (tests) or bitcode (outbox → bus). -pub fn decode_payload(message: &Message) -> Result { - let ct = message.content_type.as_str(); - if ct.contains("json") || looks_like_json(message.payload()) { - return serde_json::from_slice(message.payload()) - .map_err(|e| HandlerError::DecodeFailed(format!("json payload: {e}"))); - } - BitcodePayloadCodec::decode(message.payload()) - .map_err(|e| HandlerError::DecodeFailed(format!("bitcode payload: {e}"))) -} - -fn looks_like_json(bytes: &[u8]) -> bool { - matches!( - bytes.iter().find(|b| !b.is_ascii_whitespace()), - Some(b'{' | b'[') - ) -} - -pub fn read_model_error(e: impl std::fmt::Display) -> HandlerError { - HandlerError::Other(Box::new(std::io::Error::other(e.to_string()))) -} diff --git a/tests/e2e-ui/crates/service/src/http.rs b/tests/e2e-ui/crates/service/src/http.rs index 2102a57eb..cec92e66d 100644 --- a/tests/e2e-ui/crates/service/src/http.rs +++ b/tests/e2e-ui/crates/service/src/http.rs @@ -1,55 +1,15 @@ //! Process HTTP: GraphQL is the user edge (engine `OidcBearer`). //! //! App writes are GraphQL-only (HTTP command routes stay off). Zitadel Action -//! ingress still needs HTTP, so those two commands get an explicit edge here: -//! it checks the shared secret and dispatches them through the command ledger -//! as the ingestor — `POST /todo.create` stays 404 (suite T0). -//! -//! Note: `microsvc::router` already applies `.with_state(service)`, so handlers -//! cannot use `State>`. Capture the `Arc` in the route closures. +//! ingress still needs HTTP, so the service exposes those two commands +//! through their own edges (`Service::with_http_command` in `compose`): each +//! checks the shared secret and dispatches as the ingestor. Every other +//! command path is the service's 404 — `POST /todo.create` (suite T0) — and +//! never falls through to the UI. -use std::collections::HashMap; use std::sync::Arc; -use axum::http::{HeaderMap, StatusCode}; -use axum::response::IntoResponse; -use axum::routing::post; -use axum::Json; -use distributed::microsvc::{CausalDispatchError, Service, Session}; -use serde_json::{json, Value}; - -use crate::handlers::ingestors::{zitadel, zitadel_scrape}; - -/// The request's headers, for the ingestor's authenticity check only: they -/// are never the session a command runs with. -fn session_from_headers(headers: &HeaderMap) -> Session { - let mut vars = HashMap::new(); - for (name, value) in headers.iter() { - if let Ok(v) = value.to_str() { - vars.insert(name.as_str().to_string(), v.to_string()); - } - } - Session::from_map(vars) -} - -/// The HTTP answer of a ledgered command. -fn command_response( - command: &str, - result: Result, -) -> axum::response::Response { - match result { - Ok(value) => (StatusCode::OK, Json(value)).into_response(), - Err(error) => { - let status = StatusCode::from_u16(error.status_code()) - .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); - if status.is_server_error() { - eprintln!("command `{command}` failed: {error}"); - } - let body = json!({ "code": error.code(), "error": error.client_message() }); - (status, Json(body)).into_response() - } - } -} +use distributed::microsvc::Service; /// Compose the application's explicit public gateway without opening a listener. pub fn gateway_router( @@ -73,34 +33,16 @@ pub fn gateway_router( Route::new("auth-api", RoutePath::prefix("/api/auth"), "ui"), Route::new("ui", RoutePath::prefix("/"), "ui"), ]; - for path in [ - "/zitadel.ingress.v1", - "/zitadel.scrape.v1", - "/health", - "/healthz", - "/metrics", - "/graphiql", - ] { + for path in ["/health", "/healthz", "/metrics", "/graphiql"] { routes.push(Route::new( format!("http-{}", routes.len()), RoutePath::prefix(path), "service", )); } - // Old HTTP command URLs retain API ownership and cannot become UI HTML. - for command in service.command_specs().map_err(std::io::Error::other)? { - let path = format!("/{}", command.id); - if !routes - .iter() - .any(|route| route.path == RoutePath::prefix(&path)) - { - routes.push(Route::new( - format!("command-{}", routes.len()), - RoutePath::exact(path), - "closed", - )); - } - } + // Every command path is the service's: it answers the exposed Zitadel + // commands, and no other command URL can become UI HTML. + routes.extend(service.command_gateway_routes("service")); let gateway = GatewayConfig { bindings: vec![ Binding::new( @@ -119,7 +61,6 @@ pub fn gateway_router( }, ), Binding::new("service", BindingKind::Handler), - Binding::new("closed", BindingKind::Handler), ], routes, } @@ -165,35 +106,7 @@ pub fn gateway_router( NativeAuth::anonymous() }; - let ingress = service.clone(); - let scrape = service.clone(); - let service_routes = distributed::microsvc::router(service) - .route( - "/zitadel.ingress.v1", - post(move |headers: HeaderMap, Json(body): Json| { - let svc = ingress.clone(); - async move { - let caller = session_from_headers(&headers); - command_response( - zitadel::COMMAND, - zitadel::receive(&svc, &caller, body).await, - ) - } - }), - ) - .route( - "/zitadel.scrape.v1", - post(move |headers: HeaderMap| { - let svc = scrape.clone(); - async move { - let caller = session_from_headers(&headers); - command_response( - zitadel_scrape::COMMAND, - zitadel_scrape::receive(&svc, &caller).await, - ) - } - }), - ); + let service_routes = distributed::microsvc::router(service); NativeGateway::new( gateway, @@ -202,7 +115,6 @@ pub fn gateway_router( ("graphql".into(), graphql), ("ui".into(), NativeBinding::UiProxy { websocket: true }), ("service".into(), NativeBinding::Handler(service_routes)), - ("closed".into(), NativeBinding::Handler(axum::Router::new())), ], auth, ) diff --git a/tests/e2e-ui/crates/service/src/modules/compose.rs b/tests/e2e-ui/crates/service/src/modules/compose.rs index 75a4b8133..05eb4c1ff 100644 --- a/tests/e2e-ui/crates/service/src/modules/compose.rs +++ b/tests/e2e-ui/crates/service/src/modules/compose.rs @@ -7,6 +7,7 @@ use distributed::{AggregateBuilder, AggregateRepository, QueuedRepository}; use todo_domain::Todo; use crate::bounds::{EventStore, Locks, ReadStore}; +use crate::handlers::ingestors::{zitadel, zitadel_scrape}; use crate::modules::{blob, chat, identity, projections, todo}; /// Explicit module inventory for the e2e-ui application. @@ -56,15 +57,17 @@ where projections.chat, ); let blob = blob::routes(repo.clone(), locks, read_models.clone(), projections.blob); - let identity = identity::routes(repo, read_models); + let identity = identity::routes(repo, read_models, projections.auth); // GraphQL-only public write surface. POST /todo.* stays 404 (suite T0). - // Zitadel Action ingress still needs HTTP: the identity module's commands - // get an authenticating edge in `http::gateway_router`. + // Zitadel Action ingress still needs HTTP: its two commands are exposed + // through edges that check the shared secret and run as the ingestor. Service::new() .named("e2e-ui") .routes(todos) .routes(chat) .routes(blob) .routes(identity) + .with_http_command(zitadel::COMMAND, zitadel::http_edge) + .with_http_command(zitadel_scrape::COMMAND, zitadel_scrape::http_edge) } diff --git a/tests/e2e-ui/crates/service/src/modules/graphql.rs b/tests/e2e-ui/crates/service/src/modules/graphql.rs index 0643becd6..bc19149be 100644 --- a/tests/e2e-ui/crates/service/src/modules/graphql.rs +++ b/tests/e2e-ui/crates/service/src/modules/graphql.rs @@ -98,6 +98,7 @@ fn build_engine( projections.todo.into(), projections.chat.into(), projections.blob.into(), + projections.auth.into(), ]) .identity(identity) .graphiql(graphiql); @@ -145,6 +146,7 @@ fn pool_free_full_surface() -> Surface { projections.todo.into(), projections.chat.into(), projections.blob.into(), + projections.auth.into(), ]) .expect("e2e-ui projector topology should bind") .with_service(&service) diff --git a/tests/e2e-ui/crates/service/src/modules/identity.rs b/tests/e2e-ui/crates/service/src/modules/identity.rs index 33246bb4a..f7b61e90d 100644 --- a/tests/e2e-ui/crates/service/src/modules/identity.rs +++ b/tests/e2e-ui/crates/service/src/modules/identity.rs @@ -1,14 +1,15 @@ -//! Identity module: Zitadel ingress/scrape commands + auth_users projector. +//! Identity module: Zitadel ingress/scrape commands + the auth_users +//! projection. //! -//! No aggregate: the commands publish provider messages, which commit with -//! their ledger receipts. +//! No aggregate: the commands publish user profiles as external facts, which +//! commit with their ledger receipts; the `AUTH_USERS` projection writes them. +use distributed::graphql::SurfaceProjector; use distributed::microsvc::{ConfigurableOutboxPublisher, HasOutboxStore, HasRepo, Routes}; use distributed::AggregateRepository; use crate::bounds::{EventStore, ReadStore}; use crate::deps::AuthDeps; -use crate::handlers::events::project_auth_user; use crate::handlers::ingestors::{zitadel, zitadel_scrape}; /// Logical module id for composition inventories. @@ -17,8 +18,13 @@ pub const MODULE_ID: &str = "identity"; /// Prefix of this module's command names (they are named for the provider). pub const COMMAND_PREFIX: &str = "zitadel."; -/// Mount the Zitadel ingress and scrape commands and the auth_users projector. -pub fn routes(repo: R, read_models: S) -> Routes> +/// Mount the Zitadel ingress and scrape commands and the auth_users +/// projection. +pub fn routes( + repo: R, + read_models: S, + auth_projector: SurfaceProjector, +) -> Routes> where R: EventStore, S: ReadStore, @@ -31,6 +37,66 @@ where .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) .handle(scrape) - .events(project_auth_user::EVENTS) - .guarded(project_auth_user::guard, project_auth_user::handle) + .consume_projection(auth_projector) +} + +#[cfg(test)] +mod tests { + use distributed::bus::{InMemoryBus, RunOptions}; + use distributed::{ + ReadModelWorkspaceExt, RowKey, RowValue, SqliteLockManager, SqliteRepository, + }; + use e2e_readmodels::AuthUsers; + use serde_json::json; + + use crate::handlers::ingestors::zitadel::{ + ingestor_principal, ingestor_session, ingress_command_id, normalize_ingress_body, COMMAND, + }; + use crate::modules::compose::build_service; + + #[tokio::test] + async fn an_ingested_profile_reaches_auth_users_through_the_projection() { + let repo = SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let registry = crate::distributed_manifest().table_registry().unwrap(); + repo.bootstrap_table_schema_for_dev(®istry) + .await + .unwrap(); + let locks = SqliteLockManager::new(repo.pool().clone()); + let bus = InMemoryBus::new(); + let service = + || build_service(repo.clone(), locks.clone(), repo.clone()).with_bus(bus.clone()); + + let input = normalize_ingress_body(&json!({ + "event_id": "evt-1", + "event_type": "user.human.deactivated", + "user_id": "sub-1", + "email": "ada@example.com", + })); + service() + .dispatch_causal( + COMMAND, + &ingress_command_id(&input), + serde_json::to_value(&input).unwrap(), + ingestor_session(), + ingestor_principal(), + ) + .await + .unwrap(); + service().run(RunOptions::until_idle()).await.unwrap(); + + let row = repo + .workspace() + .load::(RowKey::new([("user_id", RowValue::String("sub-1".into()))])) + .one() + .await + .unwrap() + .expect("the projection wrote the profile") + .data; + assert_eq!(row.email, "ada@example.com"); + assert_eq!(row.display_name, "ada@example.com"); + assert_eq!(row.status, "deactivated"); + assert_eq!(row.approval_status, "pending"); + } } diff --git a/tests/e2e-ui/crates/service/src/modules/projections.rs b/tests/e2e-ui/crates/service/src/modules/projections.rs index 69b4723c7..cc42d236d 100644 --- a/tests/e2e-ui/crates/service/src/modules/projections.rs +++ b/tests/e2e-ui/crates/service/src/modules/projections.rs @@ -5,8 +5,8 @@ use distributed::graphql::{SurfaceDirectProjection, SurfaceProjector}; use distributed::LocalProjectionMountsBuilder; -use e2e_projections::{BLOB_GAMES, CHAT_MESSAGES, TODOS}; -use e2e_readmodels::{BlobGames, ChatMessages, Todos}; +use e2e_projections::{AUTH_USERS, BLOB_GAMES, CHAT_MESSAGES, TODOS}; +use e2e_readmodels::{AuthUsers, BlobGames, ChatMessages, Todos}; /// Projection surface mounts used by compose + GraphQL. #[derive(Clone)] @@ -14,6 +14,7 @@ pub struct ProjectionOwners { pub todo: SurfaceProjector, pub chat: SurfaceProjector, pub blob: SurfaceDirectProjection, + pub auth: SurfaceProjector, } /// Compile local projection mounts for the e2e-ui application. @@ -26,18 +27,21 @@ pub fn projection_owners() -> ProjectionOwners { .expect("chat mount") .direct_model::("project_blob", BLOB_GAMES, "e2e-ui-blob-v2") .expect("blob mount") + .eventual_model::("project_auth_users", AUTH_USERS, "e2e-ui-auth-users-v1") + .expect("auth users mount") .build() .expect("projection catalog"); ProjectionOwners { - todo: mounts - .projector("project_todos") - .expect("todo projector"), + todo: mounts.projector("project_todos").expect("todo projector"), chat: mounts .projector("project_chat_messages") .expect("chat projector"), blob: mounts .direct_projection("project_blob") .expect("blob direct"), + auth: mounts + .projector("project_auth_users") + .expect("auth users projector"), } } diff --git a/tests/e2e-ui/docs/zitadel-ingestor.md b/tests/e2e-ui/docs/zitadel-ingestor.md index 2ad0a1a17..6aa4db3ff 100644 --- a/tests/e2e-ui/docs/zitadel-ingestor.md +++ b/tests/e2e-ui/docs/zitadel-ingestor.md @@ -20,6 +20,11 @@ The fixture accepts the ingress secret through `x-zitadel-ingestor-secret: ` or `Authorization: Bearer `. A missing or invalid secret returns HTTP 401. +Both commands are exposed with `Service::with_http_command`: each has an HTTP +edge (`http_edge`) that checks the secret and dispatches the command as the +ingestor, so no request header reaches it. No other command has an HTTP path; +`POST /todo.create` is a 404 from the service, not the UI. + ## Start the fixture ```bash @@ -40,7 +45,7 @@ curl -sS -X POST "http://127.0.0.1:8791/zitadel.scrape.v1" \ -d '{}' ``` -The response reports `{ listed, published, skipped }`. +The response is `{ payload: { listed, published, skipped }, receipt }`. ## Verify ingress authentication @@ -77,9 +82,14 @@ curl -sS -X POST "$BASE/zitadel.ingress.v1" \ }" ``` -The request publishes `zitadel.user.human.created.v1`. After the outbox drains, -the corresponding `auth_users` row supplies chat-author and Blob Game owner -display data. +The response is `{ payload, receipt }`; `payload.published` names the Zitadel +event the delivery was (`zitadel.user.human.created.v1`). The command +publishes the user's profile as a `zitadel.user_profile` external fact +(`publish_external`) with its ledger receipt. After the outbox drains, the +`AUTH_USERS` projection (`crates/projections/src/auth_users.rs`) writes the +`auth_users` row that supplies chat-author and Blob Game owner display data. +A redelivery of the same `delivery_id` replays the receipt and publishes +nothing more. ## Verify GraphQL joins @@ -117,5 +127,6 @@ instead. ```bash cd tests/e2e-ui cargo test -p e2e-service --lib +cargo test -p e2e-projections --lib cargo test -p e2e-readmodels --lib ``` diff --git a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts index a727cb885..01d20c8da 100644 --- a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts +++ b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts @@ -1483,7 +1483,7 @@ IdentityConfig::oidc_bearer(oidc)` samples: [ { file: 'modules/compose.rs · MODULE_IDS', - caption: 'Identity is a module with no aggregate. It mounts the Zitadel commands and the `AuthUsers` projector.', + caption: 'Identity is a module with no aggregate. It mounts the Zitadel commands and the `AuthUsers` projection.', code: `pub const MODULE_IDS: &[&str] = &[ todo::MODULE_ID, chat::MODULE_ID, @@ -1493,14 +1493,19 @@ IdentityConfig::oidc_bearer(oidc)` }, { file: 'modules/identity.rs · Zitadel ingress', - caption: 'These are typed commands with no aggregate. Each provider message commits with its command ledger receipt. The HTTP edge checks the shared secret and dispatches them as the ingestor. No user role can call them.', + caption: 'These are typed commands with no aggregate. Each user profile they publish commits with its command ledger receipt. Each command has its own HTTP edge: it checks the shared secret and dispatches as the ingestor. No user role can call them, and every other command path stays closed.', code: `Routes::for_stores(repo, read_models) .typed_command(zitadel::command()) .handle(zitadel::handle) .typed_command(zitadel_scrape::command()) .handle(zitadel_scrape::Scrape(read_models.clone())) - .events(project_auth_user::EVENTS) - .guarded(project_auth_user::guard, project_auth_user::handle)` + .consume_projection(auth_projector) + +// compose.rs +Service::new() + // ... + .with_http_command(zitadel::COMMAND, zitadel::http_edge) + .with_http_command(zitadel_scrape::COMMAND, zitadel_scrape::http_edge)` }, { file: 'modules/graphql.rs · identity_from_env', @@ -1514,7 +1519,7 @@ IdentityConfig::oidc_bearer(oidc)` { id: 'events', label: '6 · Directory', - lede: 'People appear as `AuthUsers` rows. Zitadel ingest and scrape emit domain events that fill those rows. Chat author and blob owner join this directory. Do not store a second display name.', + lede: 'People appear as `AuthUsers` rows. Zitadel ingest and scrape publish user profiles as external facts, and a projection fills those rows. Chat author and blob owner join this directory. Do not store a second display name.', principle: 'Fill `AuthUsers` from identity events. Do not fill it from user commands.', samples: [ { @@ -1537,38 +1542,24 @@ pub struct AuthUsers { }` }, { - file: 'handlers/events/project_auth_user.rs', - caption: 'These Zitadel events upsert or update status on `AuthUsers`.', - code: `pub const EVENTS: &[&str] = &[ - "zitadel.user.human.created.v1", - "zitadel.user.human.updated.v1", - "zitadel.user.human.deactivated.v1", - "zitadel.user.human.reactivated.v1", - "zitadel.user.machine.created.v1", -]; + file: 'projections/auth_users.rs · AUTH_USERS', + caption: 'The ingestor publishes a `ZitadelUserProfile` with `publish_external`, identified by the delivery it came from. The projection writes it to `AuthUsers` as it is.', + code: `#[derive(Serialize, Deserialize, distributed::DomainEvent)] +#[domain_event(name = "zitadel.user_profile", version = 1)] +pub struct ZitadelUserProfile { /* the AuthUsers columns */ } -pub async fn handle( - ctx: &Context<'_, AuthDeps>, -) -> Result { - let payload: ZitadelUserPayload = decode_payload(ctx.message())?; - let name = ctx.message().name(); - let row = if name.contains("deactivated") - || name.contains("reactivated") - { - map_zitadel_user_status(name, &payload) - } else { - map_zitadel_user_upsert(name, &payload) +distributed::projection! { + pub const AUTH_USERS: ProjectionDescriptor = { + name: "project_auth_users", + version: 1, + epoch: "e2e-ui-auth-users-v1", + model: AuthUsers, + on { + events: [ZitadelUserProfile], + mutation: SaveAuthUser, + input: { user: body }, + }, }; - let store = ctx.read_model_store(); - let mut plan = ReadModelWritePlanBuilder::new(); - plan.upsert(&row).map_err(read_model_error)?; - plan.commit(store).await.map_err(read_model_error)?; - Ok(json!({ - "event": name, - "user_id": row.user_id, - "status": row.status, - "display_name": row.display_name, - })) }` } ] diff --git a/tests/services/microsvc/mod.rs b/tests/services/microsvc/mod.rs index 850dead8c..441c04f55 100644 --- a/tests/services/microsvc/mod.rs +++ b/tests/services/microsvc/mod.rs @@ -12,6 +12,8 @@ mod transport_subscribe; #[cfg(feature = "http")] mod transport_http; +#[cfg(feature = "http")] +mod transport_http_edge; #[cfg(feature = "grpc")] mod transport_grpc; diff --git a/tests/services/microsvc/transport_http_edge.rs b/tests/services/microsvc/transport_http_edge.rs new file mode 100644 index 000000000..725dd8fd4 --- /dev/null +++ b/tests/services/microsvc/transport_http_edge.rs @@ -0,0 +1,213 @@ +//! One command exposed over HTTP through its own edge +//! (`Service::with_http_command`), every other command path closed. + +use std::sync::Arc; + +use axum::http::HeaderMap; +use distributed::command_dispatch::VerifiedPrincipal; +use distributed::microsvc::{ + self, CausalDispatchError, HandlerError, HttpCommandDispatch, Routes, Service, Session, + USER_ID_KEY, +}; +use distributed::{AggregateBuilder, InMemoryRepository, Queueable}; +use serde_json::{json, Value}; + +use crate::microsvc::commands::command_id; +use crate::microsvc::handlers; +use crate::microsvc::models::counter::Counter; + +const SECRET_HEADER: &str = "x-hook-secret"; +const HOOK_USER: &str = "system:hook"; + +/// The edge of `session.identify`: a shared secret, then the hook's own +/// identity. The command ID comes from the body. +fn hook_edge(headers: &HeaderMap, body: Value) -> Result { + if headers.get(SECRET_HEADER).and_then(|v| v.to_str().ok()) != Some("s3cret") { + return Err(CausalDispatchError::Handler(HandlerError::Unauthorized( + "bad hook secret".into(), + ))); + } + let command_id = body["delivery"] + .as_str() + .ok_or_else(|| CausalDispatchError::BadRequest("delivery is missing".into()))? + .to_string(); + let mut session = Session::new(); + session.set(USER_ID_KEY, HOOK_USER); + Ok(HttpCommandDispatch { + command_id, + input: json!({}), + session, + principal: VerifiedPrincipal::internal(HOOK_USER).unwrap(), + }) +} + +/// `session.identify` exposed through [`hook_edge`]; `counter.initialize` +/// registered but not exposed. +fn hook_service() -> Arc { + Arc::new( + Service::new() + .named("hooks") + .routes( + Routes::new() + .with_repo(InMemoryRepository::new().queued().aggregate::()) + .typed_command(handlers::counter_create::command()) + .handle(handlers::counter_create::handle) + .typed_command(handlers::whoami::command()) + .handle(handlers::whoami::handle), + ) + .with_http_command(handlers::whoami::COMMAND, hook_edge), + ) +} + +async fn start_app(app: axum::Router) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + format!("http://{addr}") +} + +#[tokio::test] +async fn an_exposed_command_runs_as_its_edge_says_and_no_header_reaches_it() { + let base = start_app(microsvc::router(hook_service())).await; + let client = reqwest::Client::new(); + let delivery = command_id(); + let call = |secret: &str| { + client + .post(format!("{base}/{}", handlers::whoami::COMMAND)) + .header(SECRET_HEADER, secret) + // A caller-chosen identity: the edge's session replaces it. + .header("x-user-id", "attacker") + .header("x-roles", "admin") + .json(&json!({ "delivery": delivery })) + .send() + }; + + let refused = call("wrong").await.unwrap(); + assert_eq!(refused.status(), 401); + let body: Value = refused.json().await.unwrap(); + assert_eq!(body["code"], "UNAUTHORIZED"); + + let first = call("s3cret").await.unwrap(); + assert_eq!(first.status(), 200); + let first: Value = first.json().await.unwrap(); + assert_eq!(first["payload"], json!({ "user_id": HOOK_USER })); + assert_eq!(first["receipt"]["commandId"], delivery); + assert_eq!(first["receipt"]["state"], "succeeded"); + + // A redelivery is the same command: its receipt answers. + let again: Value = call("s3cret").await.unwrap().json().await.unwrap(); + assert_eq!(again, first); +} + +#[tokio::test] +async fn an_empty_body_reaches_the_edge_as_null_and_bad_json_never_does() { + let base = start_app(microsvc::router(hook_service())).await; + let client = reqwest::Client::new(); + let url = format!("{base}/{}", handlers::whoami::COMMAND); + + let empty = client + .post(&url) + .header(SECRET_HEADER, "s3cret") + .send() + .await + .unwrap(); + assert_eq!(empty.status(), 400); + let body: Value = empty.json().await.unwrap(); + assert_eq!(body["code"], "BAD_REQUEST"); + + let malformed = client + .post(&url) + .header(SECRET_HEADER, "s3cret") + .body("{not json") + .send() + .await + .unwrap(); + assert_eq!(malformed.status(), 400); +} + +#[tokio::test] +async fn a_command_without_an_edge_is_not_answered() { + let base = start_app(microsvc::router(hook_service())).await; + let client = reqwest::Client::new(); + + // Registered, typed, and the caller presents a trusted-looking identity + // and the hook secret: still not exposed. + let response = client + .post(format!("{base}/counter.initialize")) + .header(SECRET_HEADER, "s3cret") + .header("x-user-id", "user-1") + .header("x-roles", handlers::USER_ROLE) + .json(&json!({ "commandId": command_id(), "input": { "id": "c1" } })) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 404); +} + +#[test] +#[should_panic(expected = "does not register")] +fn an_edge_for_an_unregistered_command_fails_at_router_build() { + let service = Arc::new(Service::new().with_http_command("nope.v1", hook_edge)); + let _ = microsvc::router(service); +} + +#[cfg(feature = "gateway-native")] +#[tokio::test] +async fn every_command_path_belongs_to_the_service_not_the_ui() { + use distributed::gateway::{native::*, *}; + + let ui = start_app(axum::Router::new().fallback(|| async { "ui" })).await; + let service = hook_service(); + let mut routes = vec![Route::new("ui", RoutePath::prefix("/"), "ui")]; + routes.extend(service.command_gateway_routes("service")); + let gateway = GatewayConfig { + bindings: vec![ + Binding::new("ui", BindingKind::UiProxy { origin: ui.clone() }), + Binding::new("service", BindingKind::Handler), + ], + routes, + } + .build() + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let app = NativeGateway::new( + gateway, + NativeOptions::new(&origin), + [ + ("ui".into(), NativeBinding::UiProxy { websocket: false }), + ( + "service".into(), + NativeBinding::Handler(microsvc::router(service)), + ), + ], + NativeAuth::anonymous(), + ) + .unwrap() + .router(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let client = reqwest::Client::new(); + + let page = client.get(format!("{origin}/todos")).send().await.unwrap(); + assert_eq!(page.text().await.unwrap(), "ui"); + + let closed = client + .post(format!("{origin}/counter.initialize")) + .json(&json!({ "commandId": command_id(), "input": { "id": "c1" } })) + .send() + .await + .unwrap(); + assert_eq!(closed.status(), 404); + assert_ne!(closed.text().await.unwrap(), "ui"); + + let exposed = client + .post(format!("{origin}/{}", handlers::whoami::COMMAND)) + .header(SECRET_HEADER, "s3cret") + .json(&json!({ "delivery": command_id() })) + .send() + .await + .unwrap(); + assert_eq!(exposed.status(), 200); +}