From f90f4381d080a18e9e6af2df8956d860f17bcd8f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 07:52:51 +0400 Subject: [PATCH 01/93] fix(ai-layer): per-tool RBAC on /mcp, forward caller bearer, fix tool routes Every enterprise_mcp caller could list and call every tool, and three tools (assign_driver, get_available_drivers, get_cod_balance) hit unauthenticated /v1/internal routes with no permission check. - One MCP_TOOL_RULES table (any_of permissions + internal_route) and an MCP_HIDDEN list; mcp_tool_access() is the single decision used by both list_tools and call_tool. Unlisted tools fail closed. Partner-scoped tokens (pid set) never reach internal-route tools. - Refusals return an MCP invalid_request naming the tool and required permissions, and are audited as failed actions via record_audit. - 13 tools now forward the caller's bearer (no-op without one). - send_notification -> POST /v1/notifications/send with the engagement body shape (adds recipient/priority to the input schema); vehicle tools use /v1/fleet/vehicles[/:id]. - Tests: registry coverage, role matrix, partner scope, wildcard, list/call agreement. Co-Authored-By: Claude Sonnet 5.5 --- services/ai-layer/src/api/mcp/mod.rs | 247 +++++++++++++++++- .../ai-layer/src/infrastructure/tools/mod.rs | 154 +++++++---- 2 files changed, 339 insertions(+), 62 deletions(-) diff --git a/services/ai-layer/src/api/mcp/mod.rs b/services/ai-layer/src/api/mcp/mod.rs index 193083d4..723b438d 100644 --- a/services/ai-layer/src/api/mcp/mod.rs +++ b/services/ai-layer/src/api/mcp/mod.rs @@ -30,7 +30,8 @@ use rmcp::{ }; use serde_json::{json, Value}; -use logisticos_auth::claims::Claims; +use logisticos_agent_runtime::tools::ToolDefinition; +use logisticos_auth::{claims::Claims, rbac::permissions}; use logisticos_types::TenantId; use crate::{ @@ -46,6 +47,103 @@ use crate::{ /// this is the first consumer of it). const ENTERPRISE_MCP_FEATURE: &str = "enterprise_mcp"; +// ── Per-tool access control ──────────────────────────────────────────────── +// +// The `enterprise_mcp` feature only says the *tenant* may use MCP. What a given +// caller may do is decided per tool by the permissions on their own token, the +// same permissions the downstream service would demand. One table, one +// function (`mcp_tool_access`), used by both `list_tools` and `call_tool`. + +/// Who may call one tool over MCP. +pub struct McpToolRule { + pub tool: &'static str, + /// The caller needs at least one of these (`*` satisfies any). + pub any_of: &'static [&'static str], + /// The tool reaches an unauthenticated `/v1/internal/*` route that cannot + /// tell callers apart, so a partner-scoped token must never get there. + pub internal_route: bool, +} + +pub const MCP_TOOL_RULES: &[McpToolRule] = &[ + McpToolRule { tool: "get_shipment", any_of: &[permissions::SHIPMENT_READ], internal_route: false }, + McpToolRule { tool: "reschedule_delivery", any_of: &[permissions::SHIPMENT_UPDATE], internal_route: false }, + McpToolRule { tool: "get_available_drivers", any_of: &[permissions::DISPATCH_VIEW], internal_route: true }, + McpToolRule { tool: "assign_driver", any_of: &[permissions::DISPATCH_ASSIGN], internal_route: true }, + McpToolRule { tool: "send_notification", any_of: &[permissions::ENGAGEMENT_SEND], internal_route: false }, + McpToolRule { tool: "get_delivery_metrics", any_of: &[permissions::ANALYTICS_VIEW], internal_route: false }, + McpToolRule { tool: "get_driver_performance", any_of: &[permissions::ANALYTICS_VIEW], internal_route: false }, + McpToolRule { tool: "reconcile_cod", any_of: &[permissions::PAYMENTS_RECONCILE], internal_route: false }, + // payments' `generate_invoice` handler requires BILLING_MANAGE. + McpToolRule { tool: "generate_invoice", any_of: &[permissions::BILLING_MANAGE], internal_route: false }, + McpToolRule { tool: "get_cod_balance", any_of: &[permissions::PAYMENTS_READ], internal_route: true }, + McpToolRule { tool: "get_customer_profile", any_of: &[permissions::CUSTOMERS_VIEW], internal_route: false }, + McpToolRule { tool: "get_churn_score", any_of: &[permissions::CUSTOMERS_VIEW], internal_route: false }, + McpToolRule { tool: "get_customer_preferences", any_of: &[permissions::CUSTOMERS_VIEW], internal_route: false }, + McpToolRule { tool: "get_hub_capacity", any_of: &[permissions::FLEET_READ], internal_route: false }, + McpToolRule { tool: "get_driver_location", any_of: &[permissions::FLEET_READ], internal_route: false }, + McpToolRule { tool: "send_driver_instruction", any_of: &[permissions::FLEET_MANAGE], internal_route: false }, + McpToolRule { tool: "get_vehicle_status", any_of: &[permissions::FLEET_READ], internal_route: false }, + McpToolRule { tool: "get_fleet_availability", any_of: &[permissions::FLEET_READ], internal_route: false }, +]; + +/// Registered tools deliberately NOT exposed over MCP. Every registry tool must +/// be in `MCP_TOOL_RULES` or here (enforced by a test), so adding a tool forces +/// a decision. Anything in neither is fail-closed: unlisted and uncallable. +pub const MCP_HIDDEN: &[&str] = &[ + // No downstream route exists. + "get_zone_demand_forecast", + "schedule_dock", + // Support-agent loop marker; meaningless to a remote caller. + "escalate_to_human", +]; + +/// Why a caller may not use a tool. +#[derive(Debug, PartialEq, Eq)] +pub enum Denied { + /// Not in the table (hidden, unknown, or newly added without a decision). + NotExposed { tool: String }, + /// Lacks every permission in `any_of`. + MissingPermission { tool: &'static str, any_of: &'static [&'static str] }, + /// Partner-scoped token against a tool that reaches an unscoped internal route. + PartnerScoped { tool: &'static str }, +} + +impl Denied { + pub fn message(&self) -> String { + match self { + Denied::NotExposed { tool } => format!("Tool '{tool}' is not available over MCP"), + Denied::MissingPermission { tool, any_of } => format!( + "Tool '{tool}' requires one of the permissions: {}", + any_of.join(", ") + ), + Denied::PartnerScoped { tool } => { + format!("Tool '{tool}' is not available to partner-scoped tokens") + } + } + } +} + +/// The single access decision for `tool`. Used by `list_tools` and `call_tool`. +pub fn mcp_tool_access(claims: &Claims, tool: &str) -> Result<(), Denied> { + let rule = MCP_TOOL_RULES + .iter() + .find(|r| r.tool == tool) + .ok_or_else(|| Denied::NotExposed { tool: tool.to_string() })?; + + if !rule.any_of.iter().any(|p| claims.has_permission(p)) { + return Err(Denied::MissingPermission { tool: rule.tool, any_of: rule.any_of }); + } + if rule.internal_route && claims.pid.is_some() { + return Err(Denied::PartnerScoped { tool: rule.tool }); + } + Ok(()) +} + +/// The definitions this caller may see: exactly those `mcp_tool_access` allows. +fn accessible_definitions<'a>(claims: &Claims, defs: &'a [ToolDefinition]) -> Vec<&'a ToolDefinition> { + defs.iter().filter(|d| mcp_tool_access(claims, &d.name).is_ok()).collect() +} + #[derive(Clone)] pub struct LogisticOsMcpServer { tools: Arc, @@ -175,12 +273,10 @@ impl ServerHandler for LogisticOsMcpServer { _request: Option, context: RequestContext, ) -> Result { - Self::require_enterprise_mcp(&context)?; + let claims = Self::require_enterprise_mcp(&context)?; - let tools = self - .tools - .definitions() - .iter() + let tools = accessible_definitions(&claims, self.tools.definitions()) + .into_iter() .map(|def| { let schema = def.input_schema.as_object().cloned().unwrap_or_default(); Tool::new(def.name.clone(), def.description.clone(), schema) @@ -198,6 +294,25 @@ impl ServerHandler for LogisticOsMcpServer { let claims = Self::require_enterprise_mcp(&context)?; let client_ip = Self::client_ip_from(&context); + // Per-tool authorisation, before anything executes. A refusal is + // audited as a failed action so probing shows up in session history. + if let Err(denied) = mcp_tool_access(&claims, &request.name) { + let message = denied.message(); + let refusal = ToolResult { + tool_use_id: uuid::Uuid::new_v4().to_string(), + content: json!({ "error": message, "denied": true }), + is_error: true, + }; + let attempted = request + .arguments + .clone() + .map(Value::Object) + .unwrap_or_else(|| Value::Object(Default::default())); + self.record_audit(&claims, client_ip.as_deref(), &request.name, &attempted, &refusal) + .await; + return Err(McpError::invalid_request(message, None)); + } + // Tenant scoping always comes from the validated JWT, never from // caller-supplied arguments — a remote MCP client must not be able to // pass an arbitrary tenant_id and reach another tenant's data. @@ -251,3 +366,123 @@ pub fn streamable_http_service( StreamableHttpServerConfig::default(), ) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::infrastructure::tools::ServiceUrls; + use logisticos_auth::rbac::default_permissions_for_role; + use uuid::Uuid; + + const ROLES: &[&str] = &[ + "admin", "dispatcher", "merchant", "driver", "finance", "readonly", "customer", + "partner", "tenant_admin", "hub_scanner", "store_manager", "store_clerk", + "no_such_role", + ]; + + fn claims(perms: Vec) -> Claims { + Claims::new( + Uuid::new_v4(), Uuid::new_v4(), "t".into(), "enterprise".into(), + "u@example.com".into(), vec![], perms, 60, + ) + } + + fn role_claims(role: &str) -> Claims { + claims(default_permissions_for_role(role).iter().map(|p| p.to_string()).collect()) + } + + fn registry() -> ToolRegistry { + let u = || "http://localhost".to_string(); + ToolRegistry::new(ServiceUrls { + dispatch: u(), order_intake: u(), driver_ops: u(), payments: u(), + engagement: u(), analytics: u(), cdp: u(), hub_ops: u(), fleet: u(), + }) + } + + #[test] + fn every_registered_tool_is_either_ruled_or_hidden() { + let reg = registry(); + for def in reg.definitions() { + let ruled = MCP_TOOL_RULES.iter().any(|r| r.tool == def.name); + let hidden = MCP_HIDDEN.contains(&def.name.as_str()); + assert!( + ruled ^ hidden, + "tool '{}' must be in exactly one of MCP_TOOL_RULES / MCP_HIDDEN", + def.name + ); + } + for r in MCP_TOOL_RULES { + assert!(reg.definitions().iter().any(|d| d.name == r.tool), "{} not registered", r.tool); + } + for h in MCP_HIDDEN { + assert!(reg.definitions().iter().any(|d| d.name == *h), "{h} not registered"); + } + } + + #[test] + fn merchant_cannot_assign_invoice_or_reconcile() { + let c = role_claims("merchant"); + for t in ["assign_driver", "generate_invoice", "reconcile_cod"] { + assert!(mcp_tool_access(&c, t).is_err(), "merchant reached {t}"); + } + } + + #[test] + fn partner_scoped_admin_is_refused_internal_route_tools_only() { + let c = role_claims("admin").with_partner(Some(Uuid::new_v4())); + let internal: Vec<&McpToolRule> = MCP_TOOL_RULES.iter().filter(|r| r.internal_route).collect(); + assert_eq!(internal.len(), 3); + for r in internal { + assert_eq!(mcp_tool_access(&c, r.tool), Err(Denied::PartnerScoped { tool: r.tool })); + } + assert!(mcp_tool_access(&c, "get_shipment").is_ok()); + } + + #[test] + fn wildcard_reaches_every_ruled_tool_and_no_hidden_one() { + let c = claims(vec!["*".into()]); + for r in MCP_TOOL_RULES { + assert!(mcp_tool_access(&c, r.tool).is_ok(), "* refused {}", r.tool); + } + for h in MCP_HIDDEN { + assert_eq!(mcp_tool_access(&c, h), Err(Denied::NotExposed { tool: h.to_string() })); + } + assert!(mcp_tool_access(&c, "no_such_tool").is_err()); + } + + #[test] + fn no_permissions_reaches_nothing() { + let c = claims(vec![]); + for r in MCP_TOOL_RULES { + assert!(mcp_tool_access(&c, r.tool).is_err()); + } + } + + #[test] + fn refusal_message_names_tool_and_permission() { + let c = role_claims("merchant"); + let msg = mcp_tool_access(&c, "assign_driver").unwrap_err().message(); + assert!(msg.contains("assign_driver") && msg.contains("dispatch:assign"), "{msg}"); + } + + #[test] + fn list_and_call_agree_for_every_role_and_tool() { + let reg = registry(); + let defs = reg.definitions(); + for role in ROLES { + for pid in [None, Some(Uuid::new_v4())] { + let c = role_claims(role).with_partner(pid); + let listed: Vec<&str> = + accessible_definitions(&c, defs).iter().map(|d| d.name.as_str()).collect(); + for def in defs { + assert_eq!( + listed.contains(&def.name.as_str()), + mcp_tool_access(&c, &def.name).is_ok(), + "list/call disagree for role {role} tool {}", + def.name + ); + } + } + } + } +} diff --git a/services/ai-layer/src/infrastructure/tools/mod.rs b/services/ai-layer/src/infrastructure/tools/mod.rs index 86fc31f3..24f18221 100644 --- a/services/ai-layer/src/infrastructure/tools/mod.rs +++ b/services/ai-layer/src/infrastructure/tools/mod.rs @@ -30,6 +30,36 @@ fn authed(req: reqwest::RequestBuilder, ctx: &ToolContext) -> reqwest::RequestBu } } +/// Map the `send_notification` tool input onto engagement's +/// `SendNotificationRequest` body: `variables` become `template_vars` (all +/// values stringified, as that map is `String -> String`) and `recipient` is +/// carried inside `template_vars`, which is where the route reads it from. +fn notification_request_body(input: &Value) -> Value { + let mut vars = serde_json::Map::new(); + if let Some(obj) = input.get("variables").and_then(|v| v.as_object()) { + for (k, v) in obj { + let text = match v { + Value::String(s) => s.clone(), + other => other.to_string(), + }; + vars.insert(k.clone(), Value::String(text)); + } + } + if let Some(r) = input.get("recipient").and_then(|v| v.as_str()) { + vars.insert("recipient".into(), Value::String(r.to_string())); + } + let mut body = json!({ + "customer_id": input["customer_id"], + "channel": input["channel"], + "template_id": input["template_id"], + "template_vars": Value::Object(vars), + }); + if let Some(p) = input.get("priority").and_then(|v| v.as_str()) { + body["priority"] = Value::String(p.to_string()); + } + body +} + /// Registered tool with its handler. type ToolHandler = Arc std::pin::Pin> + Send>> + Send + Sync>; @@ -245,7 +275,7 @@ impl ToolRegistry { ); // ── send_notification ───────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "send_notification".into(), description: "Send a notification to a customer via WhatsApp, SMS, or email using a template.".into(), @@ -254,22 +284,24 @@ impl ToolRegistry { "properties": { "customer_id": {"type": "string", "format": "uuid"}, "channel": {"type": "string", "enum": ["whatsapp", "sms", "email", "push"]}, - "template_id": {"type": "string"}, - "variables": {"type": "object"} + "template_id": {"type": "string", "format": "uuid", "description": "UUID of the notification template (must match the channel)"}, + "recipient": {"type": "string", "description": "Phone number or email address to deliver to"}, + "variables": {"type": "object", "description": "Template variables (string values)"}, + "priority": {"type": "string", "enum": ["high", "normal", "low"]} }, - "required": ["customer_id", "channel", "template_id"] + "required": ["customer_id", "channel", "template_id", "recipient"] }), }, { let http = http.clone(); let url = urls.engagement.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { - let resp = http - .post(format!("{}/v1/notifications", url)) - .json(&input) + let body = notification_request_body(&input); + let resp = authed(http.post(format!("{}/v1/notifications/send", url)), &ctx) + .json(&body) .send().await? .json::().await?; Ok(resp) @@ -279,7 +311,7 @@ impl ToolRegistry { ); // ── get_delivery_metrics ────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_delivery_metrics".into(), description: "Get delivery KPIs for a tenant over a date range: success rate, on-time %, COD collection rate.".into(), @@ -295,12 +327,11 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.analytics.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { - let resp = http - .get(format!("{}/v1/analytics/kpis", url)) + let resp = authed(http.get(format!("{}/v1/analytics/kpis", url)), &ctx) .query(&[ ("from", input["from"].as_str().unwrap_or("")), ("to", input["to"].as_str().unwrap_or("")), @@ -314,7 +345,7 @@ impl ToolRegistry { ); // ── reconcile_cod ───────────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "reconcile_cod".into(), description: "Trigger COD reconciliation for a shipment that has been delivered but not credited to the merchant wallet.".into(), @@ -329,12 +360,11 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.payments.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { - let resp = http - .post(format!("{}/v1/cod/reconcile", url)) + let resp = authed(http.post(format!("{}/v1/cod/reconcile", url)), &ctx) .json(&input) .send().await? .json::().await?; @@ -345,7 +375,7 @@ impl ToolRegistry { ); // ── get_driver_performance ──────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_driver_performance".into(), description: "Get delivery performance stats for a specific driver: success rate, average delivery time, recent failures.".into(), @@ -361,12 +391,11 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.analytics.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { - let resp = http - .get(format!("{}/v1/analytics/driver-performance", url)) + let resp = authed(http.get(format!("{}/v1/analytics/driver-performance", url)), &ctx) .query(&[("driver_id", input["driver_id"].as_str().unwrap_or(""))]) .send().await? .json::().await?; @@ -377,7 +406,7 @@ impl ToolRegistry { ); // ── get_customer_profile ───────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_customer_profile".into(), description: "Retrieve a unified customer profile from the CDP including contact info, shipment history, preferences, and loyalty tier.".into(), @@ -392,16 +421,16 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.cdp.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let resp = if let Some(id) = input["customer_id"].as_str() { - http.get(format!("{}/v1/customers/{}", url, id)) + authed(http.get(format!("{}/v1/customers/{}", url, id)), &ctx) .send().await? .json::().await? } else { - http.get(format!("{}/v1/customers", url)) + authed(http.get(format!("{}/v1/customers", url)), &ctx) .query(&[("phone", input["phone"].as_str().unwrap_or(""))]) .send().await? .json::().await? @@ -413,7 +442,7 @@ impl ToolRegistry { ); // ── get_churn_score ─────────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_churn_score".into(), description: "Get the ML-predicted churn probability for a customer (0.0–1.0). Scores above 0.7 indicate high churn risk.".into(), @@ -428,13 +457,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.cdp.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["customer_id"].as_str().unwrap_or(""); - let resp = http - .get(format!("{}/v1/customers/{}/churn-score", url, id)) + let resp = authed(http.get(format!("{}/v1/customers/{}/churn-score", url, id)), &ctx) .send().await? .json::().await?; Ok(resp) @@ -444,7 +472,7 @@ impl ToolRegistry { ); // ── get_customer_preferences ────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_customer_preferences".into(), description: "Get a customer's communication preferences: preferred channel, opt-in status per channel, language, delivery time window preferences.".into(), @@ -459,13 +487,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.cdp.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["customer_id"].as_str().unwrap_or(""); - let resp = http - .get(format!("{}/v1/customers/{}/preferences", url, id)) + let resp = authed(http.get(format!("{}/v1/customers/{}/preferences", url, id)), &ctx) .send().await? .json::().await?; Ok(resp) @@ -475,7 +502,7 @@ impl ToolRegistry { ); // ── generate_invoice ────────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "generate_invoice".into(), description: "Generate or retrieve the invoice for a shipment. Returns invoice PDF URL and line items.".into(), @@ -491,13 +518,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.payments.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let shipment_id = input["shipment_id"].as_str().unwrap_or(""); - let resp = http - .post(format!("{}/v1/invoices", url)) + let resp = authed(http.post(format!("{}/v1/invoices", url)), &ctx) .json(&json!({"shipment_id": shipment_id, "force": input.get("force").and_then(|v| v.as_bool()).unwrap_or(false)})) .send().await? .json::().await?; @@ -577,7 +603,7 @@ impl ToolRegistry { ); // ── get_hub_capacity ────────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_hub_capacity".into(), description: "Get current capacity utilisation for a hub: total bays, occupied bays, inbound queue length, and estimated processing time.".into(), @@ -592,13 +618,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.hub_ops.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["hub_id"].as_str().unwrap_or(""); - let resp = http - .get(format!("{}/v1/hubs/{}/capacity", url, id)) + let resp = authed(http.get(format!("{}/v1/hubs/{}/capacity", url, id)), &ctx) .send().await? .json::().await?; Ok(resp) @@ -643,7 +668,7 @@ impl ToolRegistry { ); // ── get_vehicle_status ──────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_vehicle_status".into(), description: "Get real-time status of a specific vehicle: availability, assigned driver, current location, fuel level, and next maintenance due date.".into(), @@ -658,13 +683,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.fleet.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["vehicle_id"].as_str().unwrap_or(""); - let resp = http - .get(format!("{}/v1/vehicles/{}", url, id)) + let resp = authed(http.get(format!("{}/v1/fleet/vehicles/{}", url, id)), &ctx) .send().await? .json::().await?; Ok(resp) @@ -674,7 +698,7 @@ impl ToolRegistry { ); // ── get_fleet_availability ──────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_fleet_availability".into(), description: "Get available vehicles in the fleet filtered by type, zone, and time window. Returns vehicles sorted by proximity to a given location.".into(), @@ -691,7 +715,7 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.fleet.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { @@ -708,8 +732,7 @@ impl ToolRegistry { if let Some(at) = input["at_time"].as_str() { query.push(("at_time", at.to_string())); } - let resp = http - .get(format!("{}/v1/vehicles", url)) + let resp = authed(http.get(format!("{}/v1/fleet/vehicles", url)), &ctx) .query(&query) .send().await? .json::().await?; @@ -720,7 +743,7 @@ impl ToolRegistry { ); // ── get_driver_location ─────────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "get_driver_location".into(), description: "Get the last known GPS location and heading of a driver. Location is updated every 30 seconds by the driver app.".into(), @@ -735,13 +758,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.driver_ops.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["driver_id"].as_str().unwrap_or(""); - let resp = http - .get(format!("{}/v1/drivers/{}/location", url, id)) + let resp = authed(http.get(format!("{}/v1/drivers/{}/location", url, id)), &ctx) .send().await? .json::().await?; Ok(resp) @@ -751,7 +773,7 @@ impl ToolRegistry { ); // ── send_driver_instruction ─────────────────────────────────── - self.register( + self.register_ctx( ToolDefinition { name: "send_driver_instruction".into(), description: "Send an operational instruction to a driver's app. Use for route changes, priority reorders, pickup additions, or urgent alerts.".into(), @@ -769,13 +791,12 @@ impl ToolRegistry { { let http = http.clone(); let url = urls.driver_ops.clone(); - move |input: Value| { + move |input: Value, ctx: ToolContext| { let http = http.clone(); let url = url.clone(); Box::pin(async move { let id = input["driver_id"].as_str().unwrap_or(""); - let resp = http - .post(format!("{}/v1/drivers/{}/instructions", url, id)) + let resp = authed(http.post(format!("{}/v1/drivers/{}/instructions", url, id)), &ctx) .json(&input) .send().await? .json::().await?; @@ -869,3 +890,24 @@ impl ToolBox for ToolRegistry { ToolRegistry::execute(self, &name, input, tool_use_id, ctx).await } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notification_body_maps_to_engagement_request_shape() { + let input = json!({ + "customer_id": "c1", "channel": "sms", "template_id": "t1", + "recipient": "+639170000000", "variables": {"eta": 5, "name": "Ana"}, + "tenant_id": "ignored", + }); + let body = notification_request_body(&input); + assert_eq!(body["template_vars"]["recipient"], "+639170000000"); + assert_eq!(body["template_vars"]["eta"], "5"); + assert_eq!(body["template_vars"]["name"], "Ana"); + assert_eq!(body["channel"], "sms"); + assert!(body.get("tenant_id").is_none()); + assert!(body.get("priority").is_none()); + } +} From e78de212bb0f5e2b0798df97c0bf31edf2af246f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 07:53:23 +0400 Subject: [PATCH 02/93] refactor(admin-portal): move parseLabels out of venue page into lib Next.js page files may only export framework-allowed names. parseLabels was exported from the venues/[venueId] page; move it unchanged to src/lib/venues/parse-labels.ts and import it back into the page. Adds unit tests covering the current behaviour. Co-Authored-By: Claude Opus 5.5 --- .../app/(dashboard)/venues/[venueId]/page.tsx | 29 +----------- .../src/lib/venues/parse-labels.test.ts | 45 +++++++++++++++++++ .../src/lib/venues/parse-labels.ts | 27 +++++++++++ 3 files changed, 73 insertions(+), 28 deletions(-) create mode 100644 apps/admin-portal/src/lib/venues/parse-labels.test.ts create mode 100644 apps/admin-portal/src/lib/venues/parse-labels.ts diff --git a/apps/admin-portal/src/app/(dashboard)/venues/[venueId]/page.tsx b/apps/admin-portal/src/app/(dashboard)/venues/[venueId]/page.tsx index f40006d1..a3000984 100644 --- a/apps/admin-portal/src/app/(dashboard)/venues/[venueId]/page.tsx +++ b/apps/admin-portal/src/app/(dashboard)/venues/[venueId]/page.tsx @@ -39,38 +39,11 @@ import { type VendorRow, type VenueRow, } from "@/lib/api/venues"; +import { parseLabels } from "@/lib/venues/parse-labels"; const FIELD = "w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white placeholder:text-white/30 outline-none transition focus:border-cyan-neon/50 focus:bg-white/10"; -/** - * `"1-12, patio, 14"` -> twelve numbered labels, `patio`, and `14`. - * - * Typing twenty labels by hand is the kind of chore that ends in a venue with - * six tables set up and the rest done "later". - */ -export function parseLabels(input: string): string[] { - const out: string[] = []; - for (const rawPart of input.split(",")) { - const part = rawPart.trim(); - if (part === "") continue; - const range = part.match(/^(\d+)\s*-\s*(\d+)$/); - if (range) { - const from = Number(range[1]); - const to = Number(range[2]); - // Bounded: a typo like 1-100000 must not try to create a hundred thousand - // tables. The server caps at 200 too; this is the friendlier half. - if (to >= from && to - from < 200) { - for (let i = from; i <= to; i++) out.push(String(i)); - continue; - } - } - out.push(part); - } - // Dedupe, preserving order — two tables called "12" is a support ticket. - return Array.from(new Set(out)); -} - export default function VenueDetailPage() { const params = useParams<{ venueId: string }>(); const venueId = params.venueId; diff --git a/apps/admin-portal/src/lib/venues/parse-labels.test.ts b/apps/admin-portal/src/lib/venues/parse-labels.test.ts new file mode 100644 index 00000000..a2d30212 --- /dev/null +++ b/apps/admin-portal/src/lib/venues/parse-labels.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "@jest/globals"; + +import { parseLabels } from "@/lib/venues/parse-labels"; + +describe("parseLabels", () => { + test("expands numeric ranges and keeps plain labels in order", () => { + expect(parseLabels("1-3, patio, 5")).toEqual(["1", "2", "3", "patio", "5"]); + }); + + test("trims whitespace around each comma-separated part", () => { + expect(parseLabels(" a , b ,c")).toEqual(["a", "b", "c"]); + }); + + test("allows whitespace around the range dash", () => { + expect(parseLabels("1 - 3")).toEqual(["1", "2", "3"]); + }); + + test("empty input and blank parts produce no labels", () => { + expect(parseLabels("")).toEqual([]); + expect(parseLabels(" , , ,")).toEqual([]); + }); + + test("dedupes while preserving first-seen order", () => { + expect(parseLabels("3, 1-3, a, 3, a")).toEqual(["3", "1", "2", "a"]); + }); + + test("a reversed range is kept as a literal label, not expanded", () => { + expect(parseLabels("5-3")).toEqual(["5-3"]); + }); + + test("a range of 200 or more is kept as a literal label", () => { + expect(parseLabels("1-201")).toEqual(["1-201"]); + }); + + test("a range of exactly 200 values is still expanded", () => { + const out = parseLabels("1-200"); + expect(out).toHaveLength(200); + expect(out[0]).toBe("1"); + expect(out[199]).toBe("200"); + }); + + test("non-numeric ranges are kept as literal labels", () => { + expect(parseLabels("a-b")).toEqual(["a-b"]); + }); +}); diff --git a/apps/admin-portal/src/lib/venues/parse-labels.ts b/apps/admin-portal/src/lib/venues/parse-labels.ts new file mode 100644 index 00000000..55b0b007 --- /dev/null +++ b/apps/admin-portal/src/lib/venues/parse-labels.ts @@ -0,0 +1,27 @@ +/** + * `"1-12, patio, 14"` -> twelve numbered labels, `patio`, and `14`. + * + * Typing twenty labels by hand is the kind of chore that ends in a venue with + * six tables set up and the rest done "later". + */ +export function parseLabels(input: string): string[] { + const out: string[] = []; + for (const rawPart of input.split(",")) { + const part = rawPart.trim(); + if (part === "") continue; + const range = part.match(/^(\d+)\s*-\s*(\d+)$/); + if (range) { + const from = Number(range[1]); + const to = Number(range[2]); + // Bounded: a typo like 1-100000 must not try to create a hundred thousand + // tables. The server caps at 200 too; this is the friendlier half. + if (to >= from && to - from < 200) { + for (let i = from; i <= to; i++) out.push(String(i)); + continue; + } + } + out.push(part); + } + // Dedupe, preserving order — two tables called "12" is a support ticket. + return Array.from(new Set(out)); +} From d0d6ad27d34569e95a1a58e8978cc0e1c6ddde2e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 07:59:26 +0400 Subject: [PATCH 03/93] feat(admin-portal): upload a document on a courier's behalf from the compliance panel Adds an "Upload document" button (compliance:admin only) to the document detail panel. It opens a modal with document type, number, optional issue and expiry dates and a file picker. Files over 10 MB or outside jpeg/png/webp/pdf are refused client-side; the file is sent as bare base64 to POST /api/v1/compliance/admin/profiles/:id/documents. The panel reloads on success; server errors show inline. Pure helpers (size guard, base64 prefix strip) live in lib/compliance/upload.ts with jest tests. Co-Authored-By: Claude Opus 5.5 --- .../src/app/(dashboard)/compliance/page.tsx | 1 + .../compliance/document-detail-panel.tsx | 29 ++- .../compliance/upload-document-modal.tsx | 208 ++++++++++++++++++ apps/admin-portal/src/lib/api/compliance.ts | 34 +++ .../src/lib/compliance/upload.test.ts | 41 ++++ .../admin-portal/src/lib/compliance/upload.ts | 57 +++++ 6 files changed, 368 insertions(+), 2 deletions(-) create mode 100644 apps/admin-portal/src/components/compliance/upload-document-modal.tsx create mode 100644 apps/admin-portal/src/lib/compliance/upload.test.ts create mode 100644 apps/admin-portal/src/lib/compliance/upload.ts diff --git a/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx b/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx index c75ba626..92946545 100644 --- a/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx +++ b/apps/admin-portal/src/app/(dashboard)/compliance/page.tsx @@ -331,6 +331,7 @@ function ComplianceConsole() { onReject={handleReject} onSuspend={canAdmin ? handleSuspend : undefined} onReinstate={canAdmin ? handleReinstate : undefined} + canAdmin={canAdmin} typeNames={typeNames} entityNames={entityNames} /> diff --git a/apps/admin-portal/src/components/compliance/document-detail-panel.tsx b/apps/admin-portal/src/components/compliance/document-detail-panel.tsx index 281a22d1..d8fd111d 100644 --- a/apps/admin-portal/src/components/compliance/document-detail-panel.tsx +++ b/apps/admin-portal/src/components/compliance/document-detail-panel.tsx @@ -4,7 +4,8 @@ import { fetchProfile, fetchDocumentBlobUrl, isStoredObject } from "@/lib/api/co import type { DriverDocument } from "@/lib/api/compliance"; import { cn } from "@/lib/design-system/cn"; import { entityLabel, initialsFor, typeLabel } from "@/lib/compliance/labels"; -import { Check, X, ExternalLink, Eye, Loader2, ShieldOff, ShieldCheck } from "lucide-react"; +import { Check, X, ExternalLink, Eye, Loader2, ShieldOff, ShieldCheck, Upload } from "lucide-react"; +import { UploadDocumentModal } from "./upload-document-modal"; interface Props { profileId: string; @@ -15,6 +16,8 @@ interface Props { /** Only present for users with compliance:admin permission. */ onSuspend?: (profileId: string, reason?: string) => void; onReinstate?: (profileId: string) => void; + /** Pass true only for users with compliance:admin - shows "Upload document". */ + canAdmin?: boolean; /** `document_type_id → name`. Empty while the catalogue is loading. */ typeNames: Map; /** `entity_id → person`. Empty when the roster could not be loaded. */ @@ -57,6 +60,7 @@ export function DocumentDetailPanel({ onReject, onSuspend, onReinstate, + canAdmin, typeNames, entityNames, }: Props) { @@ -66,6 +70,9 @@ export function DocumentDetailPanel({ const [suspendReason, setSuspendReason] = useState(""); const [suspendOpen, setSuspendOpen] = useState(false); const [views, setViews] = useState>({}); + const [uploadOpen, setUploadOpen] = useState(false); + /** Bumped after an upload so the panel re-fetches without the parent's help. */ + const [localRefresh, setLocalRefresh] = useState(0); useEffect(() => { setDetail(null); @@ -79,7 +86,7 @@ export function DocumentDetailPanel({ fetchProfile(profileId) .then(setDetail) .catch(() => setDetail({ profile: null, documents: [] })); - }, [profileId, refreshKey]); + }, [profileId, refreshKey, localRefresh]); /** * Fetch one document's bytes and show it inline. @@ -222,6 +229,24 @@ export function DocumentDetailPanel({ )} + {canAdmin && ( +
+ +
+ )} + {canAdmin && uploadOpen && ( + setUploadOpen(false)} + onUploaded={() => setLocalRefresh((n) => n + 1)} + /> + )} + {/* Document list */}
{sorted.length === 0 && ( diff --git a/apps/admin-portal/src/components/compliance/upload-document-modal.tsx b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx new file mode 100644 index 00000000..501d2d1d --- /dev/null +++ b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx @@ -0,0 +1,208 @@ +"use client"; +import { useEffect, useState } from "react"; +import { motion } from "framer-motion"; +import { Loader2, Upload, X } from "lucide-react"; +import { fetchDocumentTypes, uploadDocumentOnBehalf } from "@/lib/api/compliance"; +import type { DocumentType } from "@/lib/api/compliance"; +import { + ACCEPTED_CONTENT_TYPES, + MAX_DOCUMENT_NUMBER_LENGTH, + readFileAsBase64, + validateUploadFile, +} from "@/lib/compliance/upload"; + +interface Props { + profileId: string; + onClose: () => void; + /** Called after a successful upload, before the modal closes. */ + onUploaded: () => void; +} + +const INPUT = + "w-full rounded-lg border border-glass-border bg-glass-100 px-3 py-2 text-sm text-white placeholder:text-white/25 outline-none focus:border-cyan-glow/50"; +const LABEL = "text-[11px] uppercase tracking-wider text-white/40"; + +/** + * Upload a document into a courier's profile on their behalf (compliance:admin). + * The parent decides whether to render this at all; the server enforces the + * permission regardless. + */ +export function UploadDocumentModal({ profileId, onClose, onUploaded }: Props) { + const [types, setTypes] = useState([]); + const [typesErr, setTypesErr] = useState(null); + const [typeId, setTypeId] = useState(""); + const [number, setNumber] = useState(""); + const [issue, setIssue] = useState(""); + const [expiry, setExpiry] = useState(""); + const [file, setFile] = useState(null); + const [fileErr, setFileErr] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + let live = true; + fetchDocumentTypes() + .then((t) => { if (live) setTypes(t); }) + .catch((e) => { + if (live) setTypesErr(e instanceof Error ? e.message : "Could not load document types."); + }); + return () => { live = false; }; + }, []); + + function onFile(f: File | null) { + setError(null); + if (!f) { setFile(null); setFileErr(null); return; } + const problem = validateUploadFile(f); + setFileErr(problem); + setFile(problem ? null : f); + } + + const trimmedNumber = number.trim(); + const canSubmit = + !busy && !!typeId && trimmedNumber.length > 0 && + trimmedNumber.length <= MAX_DOCUMENT_NUMBER_LENGTH && !!file; + + async function submit() { + if (!canSubmit || !file) return; + setBusy(true); + setError(null); + try { + const file_base64 = await readFileAsBase64(file); + await uploadDocumentOnBehalf(profileId, { + document_type_id: typeId, + document_number: trimmedNumber, + file_base64, + content_type: file.type, + ...(issue ? { issue_date: issue } : {}), + ...(expiry ? { expiry_date: expiry } : {}), + }); + onUploaded(); + onClose(); + } catch (e) { + setError(e instanceof Error ? e.message : "Upload failed."); + setBusy(false); + } + } + + return ( +
+
+ e.stopPropagation()} + > +
+
+ +

Upload document

+
+ +
+ +
+
+ + + {typesErr && {typesErr}} +
+ +
+ + setNumber(e.target.value)} + maxLength={MAX_DOCUMENT_NUMBER_LENGTH} + disabled={busy} + placeholder="e.g. N01-23-456789" + className={`${INPUT} font-mono`} + /> +
+ +
+
+ + setIssue(e.target.value)} + disabled={busy} className={INPUT} + /> +
+
+ + setExpiry(e.target.value)} + disabled={busy} className={INPUT} + /> +
+
+ +
+ + onFile(e.target.files?.[0] ?? null)} + disabled={busy} + className="text-xs text-white/60 file:mr-3 file:rounded-lg file:border file:border-glass-border file:bg-glass-100 file:px-3 file:py-1.5 file:text-xs file:text-white/70" + /> + {fileErr && {fileErr}} +
+ + {error && ( +
+ {error} +
+ )} +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/admin-portal/src/lib/api/compliance.ts b/apps/admin-portal/src/lib/api/compliance.ts index 91252ebe..11b669dd 100644 --- a/apps/admin-portal/src/lib/api/compliance.ts +++ b/apps/admin-portal/src/lib/api/compliance.ts @@ -131,6 +131,40 @@ export async function fetchProfile(profileId: string) { return j.data; } +export interface UploadDocumentInput { + document_type_id: string; + document_number: string; + /** Bare base64 — no `data:` prefix. */ + file_base64: string; + content_type: string; + /** `YYYY-MM-DD` */ + issue_date?: string; + /** `YYYY-MM-DD` */ + expiry_date?: string; +} + +/** + * Upload a document into someone's compliance profile on their behalf. + * Requires `compliance:admin`; the server answers 403 otherwise and 404 for a + * profile that is unknown or belongs to another tenant. + */ +export async function uploadDocumentOnBehalf( + profileId: string, + input: UploadDocumentInput, +): Promise { + const j = await okJson( + await authFetch( + `${BASE}/api/v1/compliance/admin/profiles/${encodeURIComponent(profileId)}/documents`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(input), + }, + ), + ); + return j.data; +} + export async function approveDocument(docId: string): Promise { await okJson(await authFetch(`${BASE}/api/v1/compliance/admin/documents/${docId}/approve`, { method: "POST", diff --git a/apps/admin-portal/src/lib/compliance/upload.test.ts b/apps/admin-portal/src/lib/compliance/upload.test.ts new file mode 100644 index 00000000..39f5bfb2 --- /dev/null +++ b/apps/admin-portal/src/lib/compliance/upload.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from "@jest/globals"; +import { MAX_UPLOAD_BYTES, stripDataUrlPrefix, validateUploadFile } from "./upload"; + +describe("stripDataUrlPrefix", () => { + it("removes the data: header and keeps the payload", () => { + expect(stripDataUrlPrefix("data:image/png;base64,iVBORw0KGgo=")).toBe("iVBORw0KGgo="); + expect(stripDataUrlPrefix("data:application/pdf;base64,JVBERi0x")).toBe("JVBERi0x"); + }); + + it("only cuts at the first marker, so payload content is untouched", () => { + expect(stripDataUrlPrefix("data:image/png;base64,AA;base64,BB")).toBe("AA;base64,BB"); + }); + + it("leaves a string with no prefix alone", () => { + expect(stripDataUrlPrefix("iVBORw0KGgo=")).toBe("iVBORw0KGgo="); + }); +}); + +describe("validateUploadFile", () => { + it("accepts a file at exactly the limit", () => { + expect(validateUploadFile({ size: MAX_UPLOAD_BYTES, type: "application/pdf" })).toBeNull(); + }); + + it("rejects a file one byte over 10 MB with a message naming the limit", () => { + const msg = validateUploadFile({ size: MAX_UPLOAD_BYTES + 1, type: "image/png" }); + expect(msg).toContain("10 MB"); + }); + + it("rejects an empty file", () => { + expect(validateUploadFile({ size: 0, type: "image/png" })).not.toBeNull(); + }); + + it("rejects types outside the accept list", () => { + expect(validateUploadFile({ size: 10, type: "image/gif" })).not.toBeNull(); + expect(validateUploadFile({ size: 10, type: "" })).not.toBeNull(); + }); + + it.each(["image/jpeg", "image/png", "image/webp", "application/pdf"])("accepts %s", (type) => { + expect(validateUploadFile({ size: 10, type })).toBeNull(); + }); +}); diff --git a/apps/admin-portal/src/lib/compliance/upload.ts b/apps/admin-portal/src/lib/compliance/upload.ts new file mode 100644 index 00000000..a5e4e2e9 --- /dev/null +++ b/apps/admin-portal/src/lib/compliance/upload.ts @@ -0,0 +1,57 @@ +/** + * Pure helpers behind the "Upload document" modal. + * + * Kept out of the component so the two rules that matter — the size guard and + * the base64 prefix strip — can be tested without a DOM. + */ + +/** The server rejects anything larger; failing here saves the round trip. */ +export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024; + +export const ACCEPTED_CONTENT_TYPES = [ + "image/jpeg", + "image/png", + "image/webp", + "application/pdf", +] as const; + +export const MAX_DOCUMENT_NUMBER_LENGTH = 100; + +/** + * `FileReader.readAsDataURL` yields `data:;base64,`. The API + * wants the payload alone. + */ +export function stripDataUrlPrefix(dataUrl: string): string { + const marker = ";base64,"; + const i = dataUrl.indexOf(marker); + return i === -1 ? dataUrl : dataUrl.slice(i + marker.length); +} + +/** `null` when the file is acceptable, otherwise a message fit to show the user. */ +export function validateUploadFile(file: { size: number; type: string }): string | null { + if (file.size === 0) return "The selected file is empty."; + if (file.size > MAX_UPLOAD_BYTES) { + const mb = (file.size / (1024 * 1024)).toFixed(1); + return `File is too large (${mb} MB). The limit is 10 MB.`; + } + if (!(ACCEPTED_CONTENT_TYPES as readonly string[]).includes(file.type)) { + return "Unsupported file type. Use a JPEG, PNG, WebP or PDF."; + } + return null; +} + +/** Read a file as bare base64 (no `data:` prefix). */ +export function readFileAsBase64(file: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onerror = () => reject(new Error("Could not read the selected file.")); + reader.onload = () => { + if (typeof reader.result !== "string") { + reject(new Error("Could not read the selected file.")); + return; + } + resolve(stripDataUrlPrefix(reader.result)); + }; + reader.readAsDataURL(file); + }); +} From f4b424ce8ce2b9c6699a25ce7b70f42a5fda2391 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:01:11 +0400 Subject: [PATCH 04/93] feat(compliance): admin uploads a document on a courier's behalf POST /api/v1/compliance/admin/profiles/:profile_id/documents (compliance:admin, 16 MB body limit on this route only). Shares UploadDocumentRequest and the validation/storage path with the self-upload route via api/http/upload.rs. submit_document now takes DocumentActor so the audit row records "admin" vs "driver". Document is inserted Submitted; nothing is auto-approved. Co-Authored-By: Claude Opus 5.5 --- .../compliance/src/api/http/admin_routes.rs | 108 +++++++++++ .../compliance/src/api/http/driver_routes.rs | 93 ++------- services/compliance/src/api/http/mod.rs | 7 + services/compliance/src/api/http/upload.rs | 181 ++++++++++++++++++ .../services/compliance_service.rs | 78 ++++++-- .../src/application/services/mod.rs | 2 +- 6 files changed, 374 insertions(+), 95 deletions(-) create mode 100644 services/compliance/src/api/http/upload.rs diff --git a/services/compliance/src/api/http/admin_routes.rs b/services/compliance/src/api/http/admin_routes.rs index 162a5f13..98455cc9 100644 --- a/services/compliance/src/api/http/admin_routes.rs +++ b/services/compliance/src/api/http/admin_routes.rs @@ -5,6 +5,8 @@ use serde::Deserialize; use logisticos_auth::{middleware::AuthClaims, rbac::permissions, require_permission}; use logisticos_errors::AppError; use crate::api::http::AppState; +use crate::api::http::upload::{store_upload, UploadDocumentRequest}; +use crate::application::services::DocumentActor; use crate::domain::entities::{ComplianceAuditLog, ComplianceProfile, DriverDocument}; #[derive(Deserialize)] @@ -294,6 +296,52 @@ pub async fn reinstate_profile( Ok(Json(serde_json::json!({ "data": { "ok": true } }))) } +/// The profile an admin may upload onto: it exists and is in their tenant. +/// +/// A foreign profile is `NotFound`, not `Forbidden`, so an id from another +/// tenant cannot be probed for existence on a route that writes. +fn profile_for_upload( + profile: Option, + profile_id: Uuid, + tenant_id: Uuid, +) -> Result { + profile + .filter(|p| p.tenant_id == tenant_id) + .ok_or(AppError::NotFound { resource: "ComplianceProfile", id: profile_id.to_string() }) +} + +/// `POST /admin/profiles/:profile_id/documents` -- an admin uploads a document +/// on a courier's behalf. +/// +/// The document lands as `Submitted` and is audited with the admin as actor. +/// Nothing is approved here; a reviewer still has to. +pub async fn upload_document_for_profile( + AuthClaims(claims): AuthClaims, + Path(profile_id): Path, + State(state): State>, + Json(req): Json, +) -> Result<(axum::http::StatusCode, Json), AppError> { + require_permission!(claims, permissions::COMPLIANCE_ADMIN); + let profile = profile_for_upload( + state.compliance.profiles.find_by_id(profile_id).await?, + profile_id, + claims.tenant_id, + )?; + let upload = store_upload(&state, profile.tenant_id, req).await?; + + let doc = state.compliance.submit_document( + profile.id, + upload.document_type_id, + upload.document_number, + upload.issue_date, + upload.expiry_date, + upload.file_url, + DocumentActor::Admin(claims.user_id), + ).await?; + + Ok((axum::http::StatusCode::CREATED, Json(serde_json::json!({ "data": doc })))) +} + #[cfg(test)] mod tests { use super::is_presignable; @@ -366,4 +414,64 @@ mod tests { assert_eq!(sniff_content_type(b"RIFF"), "application/octet-stream"); assert_eq!(sniff_content_type(&[b'R', b'I', b'F', b'F', 0, 0]), "application/octet-stream"); } + + use super::profile_for_upload; + use crate::domain::entities::{ComplianceProfile, ComplianceStatus}; + use logisticos_auth::{claims::Claims, rbac::permissions}; + use logisticos_errors::AppError; + use uuid::Uuid; + + fn profile(tenant_id: Uuid) -> ComplianceProfile { + ComplianceProfile { + id: Uuid::new_v4(), tenant_id, entity_type: "driver".into(), + entity_id: Uuid::new_v4(), overall_status: ComplianceStatus::PendingSubmission, + jurisdiction: "PH".into(), last_reviewed_at: None, reviewed_by: None, + suspended_at: None, created_at: chrono::Utc::now(), updated_at: chrono::Utc::now(), + } + } + + #[test] + fn a_profile_in_the_callers_tenant_is_allowed() { + let t = Uuid::new_v4(); + let p = profile(t); + assert!(profile_for_upload(Some(p.clone()), p.id, t).is_ok()); + } + + #[test] + fn a_profile_from_another_tenant_is_404() { + let p = profile(Uuid::new_v4()); + let err = profile_for_upload(Some(p.clone()), p.id, Uuid::new_v4()).unwrap_err(); + assert!(matches!(err, AppError::NotFound { .. })); + assert_eq!(err.status_code(), axum::http::StatusCode::NOT_FOUND); + } + + #[test] + fn a_missing_profile_is_404() { + let err = profile_for_upload(None, Uuid::new_v4(), Uuid::new_v4()).unwrap_err(); + assert!(matches!(err, AppError::NotFound { .. })); + } + + /// The route's gate, run exactly as the handler runs it. + fn gate(claims: &Claims) -> Result<(), AppError> { + logisticos_auth::require_permission!(claims, permissions::COMPLIANCE_ADMIN); + Ok(()) + } + + fn claims_with(perms: &[&str]) -> Claims { + Claims::new( + Uuid::new_v4(), Uuid::new_v4(), "demo".into(), "growth".into(), "a@b.test".into(), + vec![], perms.iter().map(|p| (*p).to_string()).collect(), 3600, + ) + } + + #[test] + fn a_reviewer_without_admin_is_refused_403() { + let err = gate(&claims_with(&[permissions::COMPLIANCE_REVIEW])).unwrap_err(); + assert_eq!(err.status_code(), axum::http::StatusCode::FORBIDDEN); + } + + #[test] + fn compliance_admin_passes_the_gate() { + assert!(gate(&claims_with(&[permissions::COMPLIANCE_ADMIN])).is_ok()); + } } diff --git a/services/compliance/src/api/http/driver_routes.rs b/services/compliance/src/api/http/driver_routes.rs index 2c26f2a1..e61d648d 100644 --- a/services/compliance/src/api/http/driver_routes.rs +++ b/services/compliance/src/api/http/driver_routes.rs @@ -5,6 +5,8 @@ use logisticos_auth::middleware::AuthClaims; use logisticos_errors::AppError; use serde::Deserialize; use crate::api::http::AppState; +use crate::api::http::upload::{parse_date, resolve_document_type_id, store_upload, UploadDocumentRequest}; +use crate::application::services::DocumentActor; use crate::domain::entities::ComplianceProfile; use crate::infrastructure::storage::PRESIGN_TTL_SECS; @@ -97,40 +99,6 @@ async fn resolve_profile( } } -async fn resolve_document_type_id( - state: &AppState, - type_id: Option, - type_code: Option<&str>, -) -> Result { - match type_id { - Some(id) => Ok(id), - None => { - let code = type_code.ok_or_else(|| AppError::Validation( - "document_type_id or document_type_code is required".into(), - ))?; - Ok(state.compliance.doc_types - .find_by_code(code) - .await? - .ok_or_else(|| AppError::NotFound { - resource: "DocumentType", - id: code.to_string(), - })? - .id) - } - } -} - -fn parse_date(s: Option) -> Result, AppError> { - match s { - None => Ok(None), - Some(d) => chrono::NaiveDate::parse_from_str(&d, "%Y-%m-%d") - .map(Some) - .map_err(|_| AppError::Validation( - format!("Invalid date format '{}'; expected YYYY-MM-DD", d), - )), - } -} - // ── Handlers ─────────────────────────────────────────────────────────────── pub async fn get_my_profile( @@ -241,7 +209,7 @@ pub async fn submit_document( parse_date(req.issue_date)?, parse_date(req.expiry_date)?, file_url, - claims.user_id, + DocumentActor::Driver(claims.user_id), ).await?; Ok(Json(serde_json::json!({ "data": doc }))) @@ -269,61 +237,22 @@ pub async fn get_document( /// the resulting s3:// URI. Kept for backwards compatibility (driver app, /// admin bulk ingest). New customer-app KYC uploads use the presigned flow /// (`upload-url` + `confirm`). -#[derive(Deserialize)] -pub struct UploadDocumentRequest { - #[serde(default)] - pub document_type_id: Option, - #[serde(default)] - pub document_type_code: Option, - pub document_number: String, - pub file_base64: String, - pub content_type: String, - pub issue_date: Option, - pub expiry_date: Option, -} - pub async fn upload_document( AuthClaims(claims): AuthClaims, State(state): State>, Json(req): Json, ) -> Result, AppError> { - use base64::Engine as _; - let profile = resolve_profile(&state, claims.tenant_id, claims.user_id, entity_kind_for(&claims.roles)).await?; - let document_type_id = resolve_document_type_id( - &state, - req.document_type_id, - req.document_type_code.as_deref(), - ).await?; - - let document_number = req.document_number.trim().to_owned(); - if document_number.is_empty() { - return Err(AppError::Validation("document_number cannot be empty".into())); - } - if document_number.len() > 100 { - return Err(AppError::Validation("document_number must be 100 characters or fewer".into())); - } - - let bytes = base64::engine::general_purpose::STANDARD - .decode(req.file_base64.as_bytes()) - .map_err(|e| AppError::Validation(format!("Invalid base64 payload: {e}")))?; - - let file_url = state.storage - .upload(claims.tenant_id, bytes, &req.content_type) - .await - .map_err(|e| { - tracing::error!(error = ?e, "compliance document S3 upload failed"); - AppError::Validation("Document upload failed; please try again".into()) - })?; + let upload = store_upload(&state, claims.tenant_id, req).await?; let doc = state.compliance.submit_document( profile.id, - document_type_id, - document_number, - parse_date(req.issue_date)?, - parse_date(req.expiry_date)?, - file_url, - claims.user_id, + upload.document_type_id, + upload.document_number, + upload.issue_date, + upload.expiry_date, + upload.file_url, + DocumentActor::Driver(claims.user_id), ).await?; Ok(Json(serde_json::json!({ "data": doc }))) @@ -443,7 +372,7 @@ pub async fn confirm_document( parse_date(req.issue_date)?, parse_date(req.expiry_date)?, file_url, - claims.user_id, + DocumentActor::Driver(claims.user_id), ).await?; Ok(Json(serde_json::json!({ "data": doc }))) diff --git a/services/compliance/src/api/http/mod.rs b/services/compliance/src/api/http/mod.rs index 5a8462f8..7a9fa7e2 100644 --- a/services/compliance/src/api/http/mod.rs +++ b/services/compliance/src/api/http/mod.rs @@ -89,6 +89,12 @@ fn protected_router(state: Arc) -> Router> { post(admin_routes::approve_document)) .route("/api/v1/compliance/admin/documents/:doc_id/reject", post(admin_routes::reject_document)) + // On behalf of a courier with no app: without this a field worker can + // never leave `pending_submission`. Same body limit as the self-upload + // route, scoped to this route alone. + .route("/api/v1/compliance/admin/profiles/:profile_id/documents", + post(admin_routes::upload_document_for_profile) + .layer(DefaultBodyLimit::max(MAX_UPLOAD_BODY_BYTES))) .route("/api/v1/compliance/admin/profiles/:profile_id/suspend", post(admin_routes::suspend_profile)) .route("/api/v1/compliance/admin/profiles/:profile_id/reinstate", @@ -101,5 +107,6 @@ fn protected_router(state: Arc) -> Router> { mod health; mod driver_routes; +mod upload; mod admin_routes; mod internal_routes; diff --git a/services/compliance/src/api/http/upload.rs b/services/compliance/src/api/http/upload.rs new file mode 100644 index 00000000..2f8a1e9a --- /dev/null +++ b/services/compliance/src/api/http/upload.rs @@ -0,0 +1,181 @@ +//! The base64 document upload, shared by the courier's own route +//! (`/me/documents/upload`) and the admin's on-behalf route +//! (`/admin/profiles/:profile_id/documents`). +//! +//! One body type and one validation path: the two routes differ in *who* is +//! acting and *whose* profile it lands on, never in what a valid upload is. + +use base64::Engine as _; +use chrono::NaiveDate; +use serde::Deserialize; +use uuid::Uuid; +use logisticos_errors::AppError; +use crate::api::http::AppState; + +#[derive(Deserialize)] +pub struct UploadDocumentRequest { + #[serde(default)] + pub document_type_id: Option, + #[serde(default)] + pub document_type_code: Option, + pub document_number: String, + pub file_base64: String, + pub content_type: String, + pub issue_date: Option, + pub expiry_date: Option, +} + +/// An upload that has passed validation, before any I/O beyond the type lookup. +pub struct ParsedUpload { + pub document_number: String, + pub bytes: Vec, + pub issue_date: Option, + pub expiry_date: Option, +} + +/// An upload that is validated and in storage, ready for `submit_document`. +pub struct StoredUpload { + pub document_type_id: Uuid, + pub document_number: String, + pub issue_date: Option, + pub expiry_date: Option, + pub file_url: String, +} + +pub async fn resolve_document_type_id( + state: &AppState, + type_id: Option, + type_code: Option<&str>, +) -> Result { + match type_id { + Some(id) => Ok(id), + None => { + let code = type_code.ok_or_else(|| AppError::Validation( + "document_type_id or document_type_code is required".into(), + ))?; + Ok(state.compliance.doc_types + .find_by_code(code) + .await? + .ok_or_else(|| AppError::NotFound { + resource: "DocumentType", + id: code.to_string(), + })? + .id) + } + } +} + +pub fn parse_date(s: Option) -> Result, AppError> { + match s { + None => Ok(None), + Some(d) => NaiveDate::parse_from_str(&d, "%Y-%m-%d") + .map(Some) + .map_err(|_| AppError::Validation( + format!("Invalid date format '{}'; expected YYYY-MM-DD", d), + )), + } +} + +/// Everything about the body that can be checked without a database or storage. +/// +/// Also runs before the upload, so a bad date can no longer leave an orphaned +/// object in the bucket behind a rejected request. +pub fn parse_upload(req: &UploadDocumentRequest) -> Result { + let document_number = req.document_number.trim().to_owned(); + if document_number.is_empty() { + return Err(AppError::Validation("document_number cannot be empty".into())); + } + if document_number.len() > 100 { + return Err(AppError::Validation("document_number must be 100 characters or fewer".into())); + } + + let bytes = base64::engine::general_purpose::STANDARD + .decode(req.file_base64.as_bytes()) + .map_err(|e| AppError::Validation(format!("Invalid base64 payload: {e}")))?; + + Ok(ParsedUpload { + document_number, + bytes, + issue_date: parse_date(req.issue_date.clone())?, + expiry_date: parse_date(req.expiry_date.clone())?, + }) +} + +/// Resolve the type, validate the body and put the file in tenant storage. +pub async fn store_upload( + state: &AppState, + tenant_id: Uuid, + req: UploadDocumentRequest, +) -> Result { + let document_type_id = resolve_document_type_id( + state, + req.document_type_id, + req.document_type_code.as_deref(), + ).await?; + let parsed = parse_upload(&req)?; + + let file_url = state.storage + .upload(tenant_id, parsed.bytes, &req.content_type) + .await + .map_err(|e| { + tracing::error!(error = ?e, "compliance document S3 upload failed"); + AppError::Validation("Document upload failed; please try again".into()) + })?; + + Ok(StoredUpload { + document_type_id, + document_number: parsed.document_number, + issue_date: parsed.issue_date, + expiry_date: parsed.expiry_date, + file_url, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn req() -> UploadDocumentRequest { + UploadDocumentRequest { + document_type_id: None, + document_type_code: Some("DRIVERS_LICENSE".into()), + document_number: " N01-23 ".into(), + file_base64: "aGVsbG8=".into(), + content_type: "image/jpeg".into(), + issue_date: Some("2024-01-31".into()), + expiry_date: None, + } + } + + #[test] + fn a_valid_body_parses_and_trims_the_number() { + let p = parse_upload(&req()).expect("valid"); + assert_eq!(p.document_number, "N01-23"); + assert_eq!(p.bytes, b"hello"); + assert_eq!(p.issue_date, NaiveDate::from_ymd_opt(2024, 1, 31)); + assert_eq!(p.expiry_date, None); + } + + #[test] + fn a_blank_or_oversized_number_is_a_validation_error() { + let mut r = req(); + r.document_number = " ".into(); + assert!(matches!(parse_upload(&r), Err(AppError::Validation(_)))); + r.document_number = "x".repeat(101); + assert!(matches!(parse_upload(&r), Err(AppError::Validation(_)))); + } + + #[test] + fn bad_base64_is_a_validation_error() { + let mut r = req(); + r.file_base64 = "not base64!!".into(); + assert!(matches!(parse_upload(&r), Err(AppError::Validation(_)))); + } + + #[test] + fn a_date_not_in_iso_form_is_a_validation_error() { + let mut r = req(); + r.expiry_date = Some("31/01/2030".into()); + assert!(matches!(parse_upload(&r), Err(AppError::Validation(_)))); + } +} diff --git a/services/compliance/src/application/services/compliance_service.rs b/services/compliance/src/application/services/compliance_service.rs index 9cb1cbd7..c4ab4426 100644 --- a/services/compliance/src/application/services/compliance_service.rs +++ b/services/compliance/src/application/services/compliance_service.rs @@ -15,6 +15,50 @@ use crate::domain::{ }; use crate::infrastructure::messaging::ComplianceProducer; +/// Who is putting a document on a profile. Recorded on the audit row, so a +/// document an admin submitted for a courier with no app is never attributed to +/// the courier. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DocumentActor { + Driver(Uuid), + Admin(Uuid), +} + +impl DocumentActor { + pub fn id(self) -> Uuid { + match self { + Self::Driver(id) | Self::Admin(id) => id, + } + } + + pub fn actor_type(self) -> &'static str { + match self { + Self::Driver(_) => "driver", + Self::Admin(_) => "admin", + } + } +} + +/// The `doc_submitted` audit row for one submission. +fn submission_audit_entry( + tenant_id: Uuid, + profile_id: Uuid, + doc_id: Uuid, + actor: DocumentActor, +) -> ComplianceAuditLog { + ComplianceAuditLog { + id: Uuid::new_v4(), + tenant_id, + compliance_profile_id: profile_id, + document_id: Some(doc_id), + event_type: "doc_submitted".into(), + actor_id: actor.id(), + actor_type: actor.actor_type().into(), + notes: None, + created_at: Utc::now(), + } +} + pub struct ComplianceService { pub profiles: Arc, pub documents: Arc, @@ -187,7 +231,7 @@ impl ComplianceService { issue_date: Option, expiry_date: Option, file_url: String, - actor_id: Uuid, + actor: DocumentActor, ) -> anyhow::Result { let profile = self.profiles.find_by_id(profile_id).await? .context("Profile not found")?; @@ -220,17 +264,9 @@ impl ComplianceService { }; self.documents.save(&doc).await?; - self.audit.append(&ComplianceAuditLog { - id: Uuid::new_v4(), - tenant_id: profile.tenant_id, - compliance_profile_id: profile_id, - document_id: Some(doc.id), - event_type: "doc_submitted".into(), - actor_id, - actor_type: "driver".into(), - notes: None, - created_at: Utc::now(), - }).await?; + self.audit.append(&submission_audit_entry( + profile.tenant_id, profile_id, doc.id, actor, + )).await?; self.recompute_and_publish(&profile).await?; Ok(doc) @@ -486,6 +522,24 @@ mod tests { } } + #[test] + fn a_courier_submission_is_audited_as_a_driver() { + let (t, p, d, u) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); + let e = submission_audit_entry(t, p, d, DocumentActor::Driver(u)); + assert_eq!(e.actor_type, "driver"); + assert_eq!(e.actor_id, u); + assert_eq!((e.tenant_id, e.compliance_profile_id, e.document_id), (t, p, Some(d))); + assert_eq!(e.event_type, "doc_submitted"); + } + + #[test] + fn an_on_behalf_submission_is_audited_as_the_admin() { + let (t, p, d, a) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); + let e = submission_audit_entry(t, p, d, DocumentActor::Admin(a)); + assert_eq!(e.actor_type, "admin"); + assert_eq!(e.actor_id, a); + } + #[test] fn a_new_profile_is_announced_as_not_assignable() { let p = mock_profile(ComplianceStatus::PendingSubmission); diff --git a/services/compliance/src/application/services/mod.rs b/services/compliance/src/application/services/mod.rs index 93414cf9..b881aff4 100644 --- a/services/compliance/src/application/services/mod.rs +++ b/services/compliance/src/application/services/mod.rs @@ -1,4 +1,4 @@ pub mod compliance_service; pub mod expiry_checker; -pub use compliance_service::ComplianceService; +pub use compliance_service::{ComplianceService, DocumentActor}; pub use expiry_checker::ExpiryCheckerService; From dfb45612056062280acd8dc0b112c58ba3bd66dc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:02:09 +0400 Subject: [PATCH 05/93] ops(kafka): per-partition health check and the orphaned-partition runbook A topic with an orphaned partition (on-disk topic_id from an older incarnation) looks healthy to --list and --describe but drops every keyed event hashing to that partition. 12 topics had partition 0 orphaned on the VPS broker on 2026-11-25, including order.shipment.created and pod.captured. scripts/check-kafka-partitions.sh asks for every partition's offset in one call and exits 1 when any is refused. The runbook records detection, confirmation and the repair used on 2026-08-25 and 2026-11-25. Co-Authored-By: Claude Opus 5.5 --- docs/runbooks/kafka-operations.md | 78 +++++++++++++++++++++++++++++++ scripts/check-kafka-partitions.sh | 52 +++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 scripts/check-kafka-partitions.sh diff --git a/docs/runbooks/kafka-operations.md b/docs/runbooks/kafka-operations.md index 2e95ce44..a6461535 100644 --- a/docs/runbooks/kafka-operations.md +++ b/docs/runbooks/kafka-operations.md @@ -17,6 +17,7 @@ 6. [Adding Partitions to a Topic](#6-adding-partitions-to-a-topic) 7. [Dead Letter Queue Pattern](#7-dead-letter-queue-pattern) 8. [Monitoring and Alerting](#8-monitoring-and-alerting) +9. [Orphaned Partitions (single-broker VPS)](#9-orphaned-partitions-single-broker-vps) --- @@ -820,3 +821,80 @@ via the `logisticos-msk-alerts` SNS topic: CloudWatch Alarms console: `https://ap-southeast-1.console.aws.amazon.com/cloudwatch/home?region=ap-southeast-1#alarmsV2:?search=logisticos-msk` + +--- + +## 9. Orphaned Partitions (single-broker VPS) + +### Symptom + +A topic looks healthy to `kafka-topics --describe`: the leader is set and the ISR is full. Yet keyed events for some tenants never arrive. + +- Producers log `NotLeaderOrFollower` or `MessageTimedOut` once and move on. +- Nothing downstream errors, because the event never reached it. + +### Cause + +A partition's on-disk directory belongs to an **older incarnation of the topic**: its `partition.metadata` `topic_id` differs from the live topic ID, so the broker refuses to serve that partition. + +It happens when a topic is recreated while a stale `-` directory survives on the volume, for example after a cluster-ID reset. Creating the topic can itself re-break it: the new incarnation collides with the old directory. + +Producers key by `tenant_id`, so **every** event for a tenant that hashes to the broken partition is lost. + +### Detect + +Run on the broker host: + +```bash +scripts/check-kafka-partitions.sh # exit 0 healthy, 1 broken, 2 broker unreachable +docker logs --since 1h logisticos-kafka 2>&1 | grep "does not match the topic ID" +``` + +`check-kafka-partitions.sh` issues one `kafka-get-offsets` call for all partitions. A per-topic loop takes several seconds for each broken topic and times out on ~80 topics. + +Run it after every broker restart and after creating any topic. `--list` proves nothing. + +### Confirm before touching anything + +For each broken partition, compare the live topic ID with the one on disk: + +```bash +V=/var/lib/docker/volumes/oscargomarketnet-logisticosbackend-pqfh0u_kafka_data/_data +kafka-topics --bootstrap-server localhost:9092 --describe --topic | grep -o 'TopicId: [^ ]*' +grep topic_id $V/-/partition.metadata +find $V/- -name '*.log' -printf '%s\n' # bytes of old-incarnation data +``` + +Delete a directory only when the IDs **differ**. A matching directory is live data. + +### Repair + +This was used on 2026-08-25 (2 topics) and again on 2026-11-25 (12 topics, one restart). + +1. Back up first, even if the logs are 0 bytes: `tar czf /root/orphan-parts-.tar.gz -C $V - ...` +2. `docker stop logisticos-kafka`. Only the broker; clients reconnect on their own. Do **not** touch `__consumer_offsets`. +3. `rm -rf $V/-` for each orphan. Re-check the ID mismatch in the same script, immediately before deleting. +4. `docker start logisticos-kafka`. The broker recreates each missing partition with the live topic ID. +5. Verify: + - `scripts/check-kafka-partitions.sh` → `OK` + - each repaired `partition.metadata` now carries the live ID + - consumer-group count unchanged (`kafka-consumer-groups --list | wc -l`) + - every group `Stable` + +Old-incarnation data in the backup was already unreachable: no consumer could read it under the new topic ID. Keep the tarball for forensics, not for replay. + +### 2026-11-25 incident + +12 topics had partition 0 orphaned: +- `carrier.onboarded`, `carrier.status_changed` +- `dispatch.driver.assigned` +- `driver.delivery.failed`, `driver.pickup.completed` +- `identity.tenant.created`, `identity.user.created` +- `marketing.campaign.triggered` +- `order.awb.issued`, `order.shipment.created` +- `pod.captured` +- `task.assigned` + +Five held 7–30 KB of old-incarnation data. The backup is at `/root/orphan-parts-20261125.tar.gz` on the VPS. + +After the repair, 277/277 partitions reported offsets and consumer groups stayed at 38, all `Stable`. diff --git a/scripts/check-kafka-partitions.sh b/scripts/check-kafka-partitions.sh new file mode 100644 index 00000000..0e902b45 --- /dev/null +++ b/scripts/check-kafka-partitions.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Every partition of every topic must answer an offset request. +# +# Run this ON THE BROKER HOST (it uses `docker exec`). It is the check that +# tells a healthy topic from one with an orphaned partition. `kafka-topics +# --list` and `--describe` both look fine for a broken topic: the leader is +# set, the ISR is full. Only an offset request reveals that one partition's +# on-disk log belongs to an older incarnation of the topic (a topic-ID +# mismatch), so the broker refuses to serve it. +# +# Why it matters: producers key by tenant_id. Every event for a tenant that +# hashes to a broken partition fails with NotLeaderOrFollower, is retried +# inside message.timeout.ms, and is dropped. The publishing service logs one +# error and carries on, so nothing downstream ever hears about it. +# +# 2026-11-25: 12 topics had partition 0 orphaned, including +# order.shipment.created, pod.captured, identity.user.created and +# task.assigned. Repair: docs/runbooks/kafka-operations.md, "Orphaned +# partitions". +# +# Usage: scripts/check-kafka-partitions.sh [container] [bootstrap] +# Exit: 0 if every partition reports an offset, 1 if any does not, and +# 2 if the broker cannot be queried at all. +set -euo pipefail + +CONTAINER="${1:-logisticos-kafka}" +BOOTSTRAP="${2:-localhost:9092}" + +# One request for every partition of every topic. Asking per topic takes +# several seconds for each broken one and times out over ~80 topics. +if ! out=$(docker exec "$CONTAINER" kafka-get-offsets --bootstrap-server "$BOOTSTRAP" --time -1 2>&1); then + echo "cannot query $CONTAINER: $out" >&2 + exit 2 +fi + +ok=$(printf '%s\n' "$out" | grep -cE '^[^ ]+:[0-9]+:[0-9]+$' || true) +broken=$(printf '%s\n' "$out" | grep -oE 'topic-partition [^ ]+' | sed 's/topic-partition //' | sort -u || true) + +if [ "$ok" = "0" ] && [ -z "$broken" ]; then + echo "no partitions reported. Is $CONTAINER a Kafka broker?" >&2 + exit 2 +fi + +if [ -n "$broken" ]; then + echo "BROKEN partitions ($(printf '%s\n' "$broken" | wc -l)), $ok healthy:" + printf ' %s\n' $broken + echo "Confirm the cause (grep after the last broker start, not the whole log):" + echo " docker logs --since 1h $CONTAINER 2>&1 | grep 'does not match the topic ID'" + exit 1 +fi + +echo "OK: all $ok partitions report offsets" From 100768c2b2b81dcf8120cd8227d5cd7eb79eb15e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:02:42 +0400 Subject: [PATCH 06/93] fix(admin-portal): focus management for the upload-document dialog Escape closes (not mid-submit), focus moves to the first field on open, Tab/Shift+Tab cycle inside the dialog, focus returns to the trigger on close, and the dialog is labelled by its heading. The panel now refreshes in place after a refresh on the same profile so the trigger stays mounted. Co-Authored-By: Claude Opus 5.5 --- .../compliance/document-detail-panel.tsx | 10 +++- .../compliance/upload-document-modal.tsx | 48 +++++++++++++++++-- .../src/lib/compliance/upload.test.ts | 23 ++++++++- .../admin-portal/src/lib/compliance/upload.ts | 11 +++++ 4 files changed, 86 insertions(+), 6 deletions(-) diff --git a/apps/admin-portal/src/components/compliance/document-detail-panel.tsx b/apps/admin-portal/src/components/compliance/document-detail-panel.tsx index d8fd111d..6003ac54 100644 --- a/apps/admin-portal/src/components/compliance/document-detail-panel.tsx +++ b/apps/admin-portal/src/components/compliance/document-detail-panel.tsx @@ -1,5 +1,5 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { fetchProfile, fetchDocumentBlobUrl, isStoredObject } from "@/lib/api/compliance"; import type { DriverDocument } from "@/lib/api/compliance"; import { cn } from "@/lib/design-system/cn"; @@ -74,8 +74,14 @@ export function DocumentDetailPanel({ /** Bumped after an upload so the panel re-fetches without the parent's help. */ const [localRefresh, setLocalRefresh] = useState(0); + const loadedProfileRef = useRef(null); + useEffect(() => { - setDetail(null); + // After an upload the panel refreshes in place: blanking it would unmount + // the "Upload document" trigger and lose the focus the modal returns to. + const sameProfile = loadedProfileRef.current === profileId; + loadedProfileRef.current = profileId; + if (!sameProfile) setDetail(null); // Object URLs are held by the document, not the page. Release them when // the panel switches profiles, or one courier's licence stays resident in // memory behind another courier's row for as long as the tab is open. diff --git a/apps/admin-portal/src/components/compliance/upload-document-modal.tsx b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx index 501d2d1d..09612cb0 100644 --- a/apps/admin-portal/src/components/compliance/upload-document-modal.tsx +++ b/apps/admin-portal/src/components/compliance/upload-document-modal.tsx @@ -1,5 +1,5 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { motion } from "framer-motion"; import { Loader2, Upload, X } from "lucide-react"; import { fetchDocumentTypes, uploadDocumentOnBehalf } from "@/lib/api/compliance"; @@ -7,6 +7,7 @@ import type { DocumentType } from "@/lib/api/compliance"; import { ACCEPTED_CONTENT_TYPES, MAX_DOCUMENT_NUMBER_LENGTH, + nextFocusIndex, readFileAsBase64, validateUploadFile, } from "@/lib/compliance/upload"; @@ -20,6 +21,8 @@ interface Props { const INPUT = "w-full rounded-lg border border-glass-border bg-glass-100 px-3 py-2 text-sm text-white placeholder:text-white/25 outline-none focus:border-cyan-glow/50"; +const FOCUSABLE = + 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'; const LABEL = "text-[11px] uppercase tracking-wider text-white/40"; /** @@ -39,6 +42,43 @@ export function UploadDocumentModal({ profileId, onClose, onUploaded }: Props) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); + const dialogRef = useRef(null); + const firstFieldRef = useRef(null); + // Latest busy/onClose for the document-level key handler without re-binding it. + const busyRef = useRef(busy); + busyRef.current = busy; + const onCloseRef = useRef(onClose); + onCloseRef.current = onClose; + + // Focus management: remember the trigger, move focus in, restore on close. + useEffect(() => { + const trigger = document.activeElement as HTMLElement | null; + firstFieldRef.current?.focus(); + + function onKeyDown(e: KeyboardEvent) { + if (e.key === "Escape") { + if (busyRef.current) return; + e.preventDefault(); + onCloseRef.current(); + return; + } + if (e.key !== "Tab") return; + const root = dialogRef.current; + if (!root) return; + const items = Array.from(root.querySelectorAll(FOCUSABLE)).filter( + (el) => !(el as HTMLButtonElement).disabled, + ); + const next = nextFocusIndex(items.indexOf(document.activeElement as HTMLElement), items.length, e.shiftKey); + e.preventDefault(); + if (next !== null) items[next].focus(); + } + document.addEventListener("keydown", onKeyDown); + return () => { + document.removeEventListener("keydown", onKeyDown); + trigger?.focus(); + }; + }, []); + useEffect(() => { let live = true; fetchDocumentTypes() @@ -91,9 +131,10 @@ export function UploadDocumentModal({ profileId, onClose, onUploaded }: Props) { >
-

Upload document

+

Upload document

@@ -310,6 +303,7 @@ function MarketplacePageInner() {