use serde::{Deserialize, Serialize};
use std::future::Future;
use std::pin::Pin;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServerFnErrorCode {
BadRequest,
Validation,
Unauthorized,
Forbidden,
NotFound,
Conflict,
Internal,
}
fn default_error_code() -> ServerFnErrorCode {
ServerFnErrorCode::Internal
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerFnError {
pub message: String,
#[serde(default = "default_status")]
pub status_code: u16,
#[serde(default = "default_error_code")]
pub code: ServerFnErrorCode,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerFnErrorEnvelope {
pub error: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default = "default_status")]
pub status_code: u16,
#[serde(default = "default_error_code")]
pub code: ServerFnErrorCode,
}
impl From<ServerFnError> for ServerFnErrorEnvelope {
fn from(err: ServerFnError) -> Self {
Self {
error: err.message.clone(),
message: Some(err.message),
status_code: err.status_code,
code: err.code,
}
}
}
impl From<ServerFnErrorEnvelope> for ServerFnError {
fn from(envelope: ServerFnErrorEnvelope) -> Self {
Self {
message: envelope.message.unwrap_or(envelope.error),
status_code: envelope.status_code,
code: envelope.code,
}
}
}
fn default_status() -> u16 {
500
}
impl std::fmt::Display for ServerFnError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ServerFnError({}): {}", self.status_code, self.message)
}
}
impl std::error::Error for ServerFnError {}
impl ServerFnError {
fn with_code(message: impl Into<String>, status_code: u16, code: ServerFnErrorCode) -> Self {
Self {
message: message.into(),
status_code,
code,
}
}
pub fn new(message: impl Into<String>) -> Self {
Self::with_code(message, 500, ServerFnErrorCode::Internal)
}
pub fn bad_request(message: impl Into<String>) -> Self {
Self::with_code(message, 400, ServerFnErrorCode::BadRequest)
}
pub fn validation(message: impl Into<String>) -> Self {
Self::with_code(message, 400, ServerFnErrorCode::Validation)
}
pub fn from_deserialization_error(function: &str, error: &serde_json::Error) -> Self {
Self::validation(format!(
"Validation failed for '{}': {}",
function,
redact_submitted_values(&error.to_string())
))
}
}
pub fn redact_submitted_values(message: &str) -> String {
const REDACTED: &str = "<redacted>";
const VALUE_PREFIXES: [&str; 6] = [
"unknown variant `",
"unknown field `",
"integer `",
"boolean `",
"floating point `",
"character `",
];
let mut pass_one = String::with_capacity(message.len());
let mut rest = message;
loop {
let next = VALUE_PREFIXES
.iter()
.filter_map(|prefix| rest.find(prefix).map(|at| (at, *prefix)))
.min_by_key(|(at, _)| *at);
let Some((at, prefix)) = next else { break };
let after = at + prefix.len();
let Some(len) = rest[after..].find('`') else {
break;
};
pass_one.push_str(&rest[..after]);
pass_one.push_str(REDACTED);
rest = &rest[after + len..];
}
pass_one.push_str(rest);
let mut out = String::with_capacity(pass_one.len());
let mut in_quotes = false;
let mut chars = pass_one.chars();
while let Some(ch) = chars.next() {
match ch {
'\\' if in_quotes => {
chars.next();
}
'"' if in_quotes => {
out.push_str(REDACTED);
out.push('"');
in_quotes = false;
}
'"' => {
out.push('"');
in_quotes = true;
}
_ if in_quotes => {}
_ => out.push(ch),
}
}
if in_quotes {
out.push_str(REDACTED);
}
out
}
impl ServerFnError {
pub fn unauthorized(message: impl Into<String>) -> Self {
Self::with_code(message, 401, ServerFnErrorCode::Unauthorized)
}
pub fn forbidden(message: impl Into<String>) -> Self {
Self::with_code(message, 403, ServerFnErrorCode::Forbidden)
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::with_code(message, 404, ServerFnErrorCode::NotFound)
}
pub fn conflict(message: impl Into<String>) -> Self {
Self::with_code(message, 409, ServerFnErrorCode::Conflict)
}
pub fn from_status(status_code: u16, message: impl Into<String>) -> Self {
let code = match status_code {
400 => ServerFnErrorCode::BadRequest,
401 => ServerFnErrorCode::Unauthorized,
403 => ServerFnErrorCode::Forbidden,
404 => ServerFnErrorCode::NotFound,
409 => ServerFnErrorCode::Conflict,
_ => ServerFnErrorCode::Internal,
};
Self::with_code(message, status_code, code)
}
}
pub fn validate_server_fn(
condition: bool,
message: impl Into<String>,
) -> Result<(), ServerFnError> {
if condition {
Ok(())
} else {
Err(ServerFnError::validation(message))
}
}
pub fn require_server_fn_auth(
authenticated: bool,
message: impl Into<String>,
) -> Result<(), ServerFnError> {
if authenticated {
Ok(())
} else {
Err(ServerFnError::unauthorized(message))
}
}
pub fn require_server_fn_scope<I, S>(scopes: I, required: &str) -> Result<(), ServerFnError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
if scopes.into_iter().any(|scope| scope.as_ref() == required) {
Ok(())
} else {
Err(ServerFnError::forbidden(format!(
"missing required scope '{required}'"
)))
}
}
const MAX_FALLBACK_ERROR_BODY_LEN: usize = 2_048;
pub fn decode_server_fn_error_body(body: &str, fallback_status_code: u16) -> ServerFnError {
if let Ok(envelope) = serde_json::from_str::<ServerFnErrorEnvelope>(body) {
return envelope.into();
}
if let Ok(err) = serde_json::from_str::<ServerFnError>(body) {
return err;
}
let truncated = if body.len() > MAX_FALLBACK_ERROR_BODY_LEN {
let mut end = MAX_FALLBACK_ERROR_BODY_LEN;
while !body.is_char_boundary(end) {
end -= 1;
}
&body[..end]
} else {
body
};
ServerFnError::from_status(fallback_status_code, truncated)
}
impl From<serde_json::Error> for ServerFnError {
fn from(err: serde_json::Error) -> Self {
Self::bad_request(format!("serialization error: {}", err))
}
}
impl From<anyhow::Error> for ServerFnError {
fn from(err: anyhow::Error) -> Self {
tracing::error!(error = ?err, "server_fn_internal_error");
Self::new("internal server error")
}
}
#[cfg(feature = "rest")]
impl axum::response::IntoResponse for ServerFnError {
fn into_response(self) -> axum::response::Response {
let status = axum::http::StatusCode::from_u16(self.status_code)
.unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
let body = ServerFnErrorEnvelope::from(self);
(status, axum::Json(body)).into_response()
}
}
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
#[cfg(feature = "rest")]
pub struct ServerFnRegistration {
pub name: &'static str,
pub url: &'static str,
pub handler: fn(serde_json::Value) -> BoxFuture<axum::response::Response>,
}
#[cfg(not(feature = "rest"))]
pub struct ServerFnRegistration {
pub name: &'static str,
pub url: &'static str,
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ServerFnRegistration>();
};
#[cfg(feature = "rest")]
pub trait ServerFn {
const NAME: &'static str;
const URL: &'static str;
fn dispatch(args: serde_json::Value) -> BoxFuture<axum::response::Response>;
}
#[cfg(feature = "rest")]
pub fn server_fn_router(registrations: &'static [ServerFnRegistration]) -> axum::Router {
use axum::routing::post;
let mut router = axum::Router::new();
for reg in registrations {
let handler = reg.handler;
router = router.route(
reg.url,
post(
move |axum::Json(args): axum::Json<serde_json::Value>| async move {
handler(args).await
},
),
);
}
router
}
#[cfg(feature = "rest")]
pub fn server_fn_dispatch_router(registrations: &'static [ServerFnRegistration]) -> axum::Router {
router_with_dispatch(registrations)
}
#[cfg(feature = "rest")]
fn router_with_dispatch(registrations: &'static [ServerFnRegistration]) -> axum::Router {
use axum::extract::Path;
use axum::response::IntoResponse;
axum::Router::new().route(
"/api/rpc/{fn_name}",
axum::routing::post(
move |Path(fn_name): Path<String>,
axum::Json(args): axum::Json<serde_json::Value>| async move {
for reg in registrations {
if reg.name == fn_name {
return (reg.handler)(args).await;
}
}
ServerFnError::not_found(format!("server function '{}' not found", fn_name))
.into_response()
},
),
)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServerEvent {
pub event: Option<String>,
pub data: String,
pub id: Option<String>,
}
#[derive(Debug, Default)]
pub struct SseParser {
line: String,
pending_cr: bool,
event: Option<String>,
data: Vec<String>,
id: Option<String>,
}
impl SseParser {
pub fn push(&mut self, text: &str) -> Vec<ServerEvent> {
let mut out = Vec::new();
for ch in text.chars() {
if self.pending_cr {
self.pending_cr = false;
if ch == '\n' {
continue;
}
}
match ch {
'\r' => {
self.pending_cr = true;
self.end_line(&mut out);
}
'\n' => self.end_line(&mut out),
c => self.line.push(c),
}
}
out
}
pub fn finish(&mut self) -> Vec<ServerEvent> {
*self = Self::default();
Vec::new()
}
fn end_line(&mut self, out: &mut Vec<ServerEvent>) {
let line = std::mem::take(&mut self.line);
if line.is_empty() {
if !self.data.is_empty() {
out.push(ServerEvent {
event: self.event.take(),
data: std::mem::take(&mut self.data).join("\n"),
id: self.id.clone(),
});
} else {
self.event = None;
}
return;
}
if line.starts_with(':') {
return;
}
let (field, value) = match line.split_once(':') {
Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
None => (line.as_str(), ""),
};
match field {
"event" => self.event = Some(value.to_string()),
"data" => self.data.push(value.to_string()),
"id" if !value.contains('\0') => self.id = Some(value.to_string()),
_ => {}
}
}
}
#[cfg(target_arch = "wasm32")]
pub async fn call_server_fn<A: Serialize, T: serde::de::DeserializeOwned>(
url: &str,
args: &A,
) -> Result<T, ServerFnError> {
use wasm_bindgen_futures::JsFuture;
let resp = post_server_fn(url, args).await?;
let text = JsFuture::from(
resp.text()
.map_err(|_| ServerFnError::new("failed to read response body"))?,
)
.await
.map_err(|_| ServerFnError::new("failed to await response text"))?;
let text_str = text
.as_string()
.ok_or_else(|| ServerFnError::new("response is not a string"))?;
if resp.ok() {
serde_json::from_str(&text_str).map_err(|e| ServerFnError::new(e.to_string()))
} else {
Err(decode_server_fn_error_body(&text_str, resp.status()))
}
}
#[cfg(target_arch = "wasm32")]
pub async fn call_server_fn_stream<A: Serialize>(
url: &str,
args: &A,
) -> Result<ServerEventStream, ServerFnError> {
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
let resp = post_server_fn(url, args).await?;
if !resp.ok() {
let text = JsFuture::from(
resp.text()
.map_err(|_| ServerFnError::new("failed to read response body"))?,
)
.await
.ok()
.and_then(|v| v.as_string())
.unwrap_or_default();
return Err(decode_server_fn_error_body(&text, resp.status()));
}
let body = resp
.body()
.ok_or_else(|| ServerFnError::new("stream response has no body"))?;
let reader: web_sys::ReadableStreamDefaultReader = body
.get_reader()
.dyn_into()
.map_err(|_| ServerFnError::new("stream reader cast failed"))?;
Ok(ServerEventStream {
reader,
parser: SseParser::default(),
ready: std::collections::VecDeque::new(),
utf8_carry: Vec::new(),
done: false,
})
}
#[cfg(target_arch = "wasm32")]
pub struct ServerEventStream {
reader: web_sys::ReadableStreamDefaultReader,
parser: SseParser,
ready: std::collections::VecDeque<ServerEvent>,
utf8_carry: Vec<u8>,
done: bool,
}
#[cfg(target_arch = "wasm32")]
impl ServerEventStream {
pub async fn next(&mut self) -> Option<Result<ServerEvent, ServerFnError>> {
use wasm_bindgen_futures::JsFuture;
loop {
if let Some(event) = self.ready.pop_front() {
return Some(Ok(event));
}
if self.done {
return None;
}
let chunk = match JsFuture::from(self.reader.read()).await {
Ok(chunk) => chunk,
Err(_) => {
self.done = true;
return Some(Err(ServerFnError::new("failed to read event stream")));
}
};
let done = js_sys::Reflect::get(&chunk, &"done".into())
.ok()
.and_then(|v| v.as_bool())
.unwrap_or(true);
if done {
self.done = true;
self.ready.extend(self.parser.finish());
continue;
}
let Ok(value) = js_sys::Reflect::get(&chunk, &"value".into()) else {
continue;
};
self.utf8_carry
.extend(js_sys::Uint8Array::new(&value).to_vec());
let text = take_complete_utf8(&mut self.utf8_carry);
self.ready.extend(self.parser.push(&text));
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
fn take_complete_utf8(buf: &mut Vec<u8>) -> String {
match std::str::from_utf8(buf) {
Ok(text) => {
let text = text.to_string();
buf.clear();
text
}
Err(err) if err.error_len().is_none() => {
let valid = err.valid_up_to();
let text = String::from_utf8_lossy(&buf[..valid]).into_owned();
buf.drain(..valid);
text
}
Err(_) => {
let text = String::from_utf8_lossy(buf).into_owned();
buf.clear();
text
}
}
}
#[cfg(target_arch = "wasm32")]
async fn post_server_fn<A: Serialize>(
url: &str,
args: &A,
) -> Result<web_sys::Response, ServerFnError> {
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
let window = web_sys::window().ok_or_else(|| ServerFnError::new("no window object"))?;
let body = serde_json::to_string(args).map_err(|e| ServerFnError::new(e.to_string()))?;
let opts = web_sys::RequestInit::new();
opts.set_method("POST");
opts.set_body(&wasm_bindgen::JsValue::from_str(&body));
let request = web_sys::Request::new_with_str_and_init(url, &opts)
.map_err(|_| ServerFnError::new("failed to create request"))?;
request
.headers()
.set("Content-Type", "application/json")
.map_err(|_| ServerFnError::new("failed to set content-type"))?;
if let Some(token) = fetch_csrf_token(&window).await {
let _ = request.headers().set(crate::csrf::CSRF_HEADER_NAME, &token);
}
let resp_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(|_| ServerFnError::new("fetch failed"))?;
resp_value
.dyn_into()
.map_err(|_| ServerFnError::new("response cast failed"))
}
#[cfg(target_arch = "wasm32")]
async fn fetch_csrf_token(window: &web_sys::Window) -> Option<String> {
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
let opts = web_sys::RequestInit::new();
opts.set_method("GET");
let request =
web_sys::Request::new_with_str_and_init(crate::csrf::CSRF_TOKEN_ENDPOINT_PATH, &opts)
.ok()?;
let resp_value = JsFuture::from(window.fetch_with_request(&request))
.await
.ok()?;
let resp: web_sys::Response = resp_value.dyn_into().ok()?;
if !resp.ok() {
return None;
}
let text = JsFuture::from(resp.text().ok()?).await.ok()?;
let text = text.as_string()?;
let parsed: serde_json::Value = serde_json::from_str(&text).ok()?;
parsed
.get(crate::csrf::CSRF_TOKEN_JSON_FIELD)?
.as_str()
.map(ToString::to_string)
}
#[cfg(not(target_arch = "wasm32"))]
const DEFAULT_SERVER_FN_TIMEOUT_MS: u64 = 30_000;
#[cfg(not(target_arch = "wasm32"))]
fn native_rpc_client() -> &'static reqwest::Client {
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
CLIENT.get_or_init(|| {
let timeout_ms = std::env::var("KRAB_SERVER_FN_TIMEOUT_MS")
.ok()
.and_then(|raw| raw.parse::<u64>().ok())
.filter(|ms| *ms > 0)
.unwrap_or(DEFAULT_SERVER_FN_TIMEOUT_MS);
reqwest::Client::builder()
.timeout(std::time::Duration::from_millis(timeout_ms))
.build()
.unwrap_or_default()
})
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn call_server_fn<A: Serialize, T: serde::de::DeserializeOwned>(
url: &str,
args: &A,
) -> Result<T, ServerFnError> {
let response = native_rpc_client()
.post(url)
.json(args)
.send()
.await
.map_err(|err| ServerFnError::new(format!("request failed: {err}")))?;
let status = response.status();
let body = response
.text()
.await
.map_err(|err| ServerFnError::new(format!("failed to read response body: {err}")))?;
if status.is_success() {
serde_json::from_str(&body)
.map_err(|err| ServerFnError::new(format!("invalid success payload: {err}")))
} else {
Err(decode_server_fn_error_body(&body, status.as_u16()))
}
}
#[macro_export]
macro_rules! collect_server_fns {
($($fn_name:ident),* $(,)?) => {
[
$($crate::server_fn::ServerFnRegistration {
name: <$fn_name as $crate::server_fn::ServerFn>::NAME,
url: <$fn_name as $crate::server_fn::ServerFn>::URL,
handler: <$fn_name as $crate::server_fn::ServerFn>::dispatch,
}),*
]
};
}
#[cfg(test)]
mod sse_tests {
use super::{take_complete_utf8, ServerEvent, SseParser};
fn ev(event: Option<&str>, data: &str, id: Option<&str>) -> ServerEvent {
ServerEvent {
event: event.map(str::to_string),
data: data.to_string(),
id: id.map(str::to_string),
}
}
#[test]
fn parses_what_axum_sse_emits() {
let mut p = SseParser::default();
let events = p.push("event: project\ndata: p-1\n\ndata: two\ndata: lines\nid: 7\n\n");
assert_eq!(
events,
vec![
ev(Some("project"), "p-1", None),
ev(None, "two\nlines", Some("7"))
]
);
}
#[test]
fn events_split_across_chunks_and_line_endings() {
let mut p = SseParser::default();
assert!(p.push("data: hel").is_empty());
assert!(p.push("lo\r").is_empty());
assert_eq!(p.push("\n\r\n"), vec![ev(None, "hello", None)]);
assert_eq!(
p.push("data:no-space\r\r"),
vec![ev(None, "no-space", None)]
);
}
#[test]
fn comments_and_unknown_fields_are_ignored_and_empty_events_dropped() {
let mut p = SseParser::default();
assert!(p.push(": keep-alive\nretry: 10\nevent: x\n\n").is_empty());
assert_eq!(p.push("data: y\n\n"), vec![ev(None, "y", None)]);
assert!(p.push("data: partial").is_empty());
assert!(p.finish().is_empty());
}
#[test]
fn utf8_split_across_chunks_is_held_back() {
let bytes = "é".as_bytes();
let mut buf = vec![b'a', bytes[0]];
assert_eq!(take_complete_utf8(&mut buf), "a");
buf.push(bytes[1]);
assert_eq!(take_complete_utf8(&mut buf), "é");
assert!(buf.is_empty());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redaction_keeps_the_field_name_a_caller_needs() {
let message = redact_submitted_values("missing field `excited`");
assert_eq!(message, "missing field `excited`");
}
#[test]
fn redaction_removes_a_submitted_value_but_keeps_the_expected_type() {
let message = redact_submitted_values("invalid type: string \"hunter2\", expected u64");
assert!(!message.contains("hunter2"), "value leaked: {message}");
assert!(
message.contains("expected u64"),
"diagnostic lost: {message}"
);
}
#[test]
fn redaction_removes_an_unknown_variant_but_keeps_the_permitted_set() {
let message =
redact_submitted_values("unknown variant `hunter2`, expected one of `read`, `write`");
assert!(!message.contains("hunter2"), "value leaked: {message}");
assert!(message.contains("`read`"), "permitted set lost: {message}");
assert!(message.contains("`write`"), "permitted set lost: {message}");
}
#[test]
fn redaction_removes_non_string_values_too() {
for (message, secret) in [
(
"invalid type: integer `123456`, expected a string",
"123456",
),
("invalid type: boolean `true`, expected a string", "true"),
("invalid type: floating point `1.5`, expected u64", "1.5"),
("invalid value: character `Z`, expected a digit", "Z"),
] {
let redacted = redact_submitted_values(message);
assert!(!redacted.contains(secret), "value leaked: {redacted}");
assert!(redacted.contains("expected"), "diagnostic lost: {redacted}");
}
}
#[test]
fn redaction_honours_escaped_quotes_inside_a_string_value() {
let redacted =
redact_submitted_values(r#"invalid type: string "x\"hunter2", expected u64"#);
assert!(
!redacted.contains("hunter2"),
"value leaked past an escaped quote: {redacted}"
);
assert!(
redacted.contains("expected u64"),
"diagnostic lost: {redacted}"
);
}
#[test]
fn redaction_handles_a_message_with_several_values() {
let redacted = redact_submitted_values(
r#"invalid value: integer `42`, expected one of `read`, `write`; got string "hunter2""#,
);
assert!(!redacted.contains("42"), "integer leaked: {redacted}");
assert!(!redacted.contains("hunter2"), "string leaked: {redacted}");
assert!(
redacted.contains("`read`") && redacted.contains("`write`"),
"schema lost: {redacted}"
);
}
#[test]
fn redaction_survives_an_unterminated_quote() {
let message = redact_submitted_values("invalid type: string \"secret");
assert!(!message.contains("secret"), "value leaked: {message}");
}
#[test]
fn deserialization_errors_name_the_function_and_drop_the_value() {
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct Args {
count: u64,
}
let error =
serde_json::from_value::<Args>(serde_json::json!({ "count": "hunter2" })).unwrap_err();
let err = ServerFnError::from_deserialization_error("greet", &error);
assert_eq!(err.status_code, 400);
assert!(err.message.contains("greet"), "function lost: {err}");
assert!(!err.message.contains("hunter2"), "value leaked: {err}");
}
#[test]
fn server_fn_error_display() {
let err = ServerFnError::new("something went wrong");
assert_eq!(err.to_string(), "ServerFnError(500): something went wrong");
assert_eq!(err.status_code, 500);
}
#[test]
fn server_fn_error_constructors() {
assert_eq!(ServerFnError::bad_request("bad").status_code, 400);
assert_eq!(
ServerFnError::validation("bad input").code,
ServerFnErrorCode::Validation
);
assert_eq!(ServerFnError::unauthorized("no").status_code, 401);
assert_eq!(ServerFnError::forbidden("denied").status_code, 403);
assert_eq!(ServerFnError::not_found("gone").status_code, 404);
assert_eq!(ServerFnError::conflict("dup").status_code, 409);
}
#[test]
fn server_fn_error_serialization() {
let err = ServerFnError::bad_request("invalid input");
let json = serde_json::to_string(&err).unwrap();
let parsed: ServerFnError = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.message, "invalid input");
assert_eq!(parsed.status_code, 400);
assert_eq!(parsed.code, ServerFnErrorCode::BadRequest);
}
#[test]
fn server_fn_error_deserializes_legacy_error_envelope() {
let parsed =
decode_server_fn_error_body(r#"{"error":"invalid payload","status_code":400}"#, 500);
assert_eq!(parsed.message, "invalid payload");
assert_eq!(parsed.status_code, 400);
assert_eq!(parsed.code, ServerFnErrorCode::Internal);
}
#[test]
fn server_fn_error_envelope_is_client_deserializable() {
let envelope = ServerFnErrorEnvelope::from(ServerFnError::validation("missing field"));
let json = serde_json::to_string(&envelope).unwrap();
let parsed = decode_server_fn_error_body(&json, 500);
assert_eq!(parsed.message, "missing field");
assert_eq!(parsed.status_code, 400);
assert_eq!(parsed.code, ServerFnErrorCode::Validation);
}
#[test]
fn validation_and_auth_helpers_return_typed_errors() {
assert!(validate_server_fn(true, "ok").is_ok());
let validation = validate_server_fn(false, "name is required").unwrap_err();
assert_eq!(validation.status_code, 400);
assert_eq!(validation.code, ServerFnErrorCode::Validation);
let unauthorized = require_server_fn_auth(false, "login required").unwrap_err();
assert_eq!(unauthorized.status_code, 401);
assert_eq!(unauthorized.code, ServerFnErrorCode::Unauthorized);
let forbidden = require_server_fn_scope(["users:read"], "users:write").unwrap_err();
assert_eq!(forbidden.status_code, 403);
assert_eq!(forbidden.code, ServerFnErrorCode::Forbidden);
}
#[test]
fn server_fn_error_from_anyhow_does_not_leak_internal_detail() {
let anyhow_err = anyhow::anyhow!("postgres://user:s3cret@db/prod: connection refused");
let err: ServerFnError = anyhow_err.into();
assert_eq!(err.status_code, 500);
assert_eq!(err.message, "internal server error");
assert!(!err.message.contains("s3cret"));
}
#[test]
fn decode_server_fn_error_body_truncates_oversized_fallback_bodies() {
let body = "x".repeat(MAX_FALLBACK_ERROR_BODY_LEN * 4);
let err = decode_server_fn_error_body(&body, 502);
assert_eq!(err.status_code, 502);
assert_eq!(err.message.len(), MAX_FALLBACK_ERROR_BODY_LEN);
}
#[test]
fn server_fn_error_from_serde() {
let serde_err = serde_json::from_str::<String>("not valid json").unwrap_err();
let err: ServerFnError = serde_err.into();
assert_eq!(err.status_code, 400);
assert!(err.message.contains("serialization error"));
}
}