Compare commits

...
3 Commits
16 changed files with 632 additions and 53 deletions

No files matched your search

+13 -6
View File
@@ -267,12 +267,19 @@ uses `tracing`; set `RUST_LOG` to control verbosity (default `info`).
The config is the same JSON the other Strata tools use. Keys acted on here include
`exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`,
`sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database),
`workspace_root` (framework root), `system_prompt` (general default), `language`
(UI/prompt catalog, default `it`), and the optional `startup_timeout_secs` /
`silence_timeout_secs`. Everything else (`arch`,
`mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored —
unknown keys never break startup.
`max_new` (default generation budget, see below), `sampling`, `api_key`,
`allowed_hosts`, `db_path` (GUI session database), `workspace_root` (framework
root), `system_prompt` (general default), `language` (UI/prompt catalog, default
`it`), and the optional `startup_timeout_secs` / `silence_timeout_secs`. Everything
else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported
as ignored — unknown keys never break startup.
**Generation budget (`max_new`).** When neither the request nor the session sets
`max_tokens`, generation is capped at `max_new` tokens (config, default **16384**).
Reasoning and answer share this ceiling: it was raised from 2048 because extended
chain-of-thought was being truncated mid-reasoning (`finish_reason: length`, empty
answer). The model still stops early at EOS, so the larger cap only matters when it
would otherwise run out; a per-session/per-request `max_tokens` still overrides it.
### Localization (i18n)
+48 -5
View File
@@ -79,7 +79,8 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
.replace("\r\n", "\n")
.replace('\r', "\n");
let store = store.clone();
let sid = session_id.to_string();
let res = tokio::task::spawn_blocking(move || -> Result<String> {
@@ -91,8 +92,8 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
if key.chars().count() > MAX_KEY_CHARS {
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
}
if key.contains('\n') {
return Ok("error: key must be a single line".into());
if key.chars().any(|c| c.is_control()) {
return Ok("error: key must be a single line (no control characters)".into());
}
if text.is_empty() {
return Ok("error: notepad set requires non-empty 'text'".into());
@@ -104,12 +105,14 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
));
}
let entries = store.notepad(&sid)?;
// Budget the RENDERED header (`key: text` per line), not just the
// text: excluding keys let many long keys blow past the ceiling.
let others: usize = entries
.iter()
.filter(|e| e.key != key)
.map(|e| e.text.chars().count())
.map(|e| e.key.chars().count() + 2 + e.text.chars().count())
.sum();
let total = others + nlen;
let total = others + key.chars().count() + 2 + nlen;
if total > MAX_TOTAL_CHARS {
return Ok(format!(
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
@@ -240,4 +243,44 @@ mod tests {
assert_eq!(d["function"]["name"], "notepad");
assert_eq!(d["function"]["parameters"]["required"][0], "action");
}
#[tokio::test]
async fn budget_counts_keys_and_rejects_control_chars() {
let (store, sid) = setup();
// A carriage return (or any control char) in the key is rejected.
let out = execute(
&store,
&sid,
&json!({"action":"set","key":"a\rb","text":"x"}),
)
.await;
assert!(out.contains("single line"), "{out}");
// Keys count toward the budget: long keys + 1-char text hit the ceiling
// after ~125 entries, not the 8000 the text-only budget would allow.
let prefix = "k".repeat(60);
let mut refused = false;
for i in 0..200 {
let key = format!("{prefix}{i}");
let out = execute(&store, &sid, &json!({"action":"set","key":key,"text":"x"})).await;
if out.contains("full") {
refused = true;
break;
}
}
assert!(refused, "key length must count toward the notepad budget");
assert!(store.notepad(&sid).unwrap().len() < 200);
}
#[tokio::test]
async fn text_carriage_returns_normalized() {
let (store, sid) = setup();
execute(
&store,
&sid,
&json!({"action":"set","key":"k","text":"a\r\nb\rc"}),
)
.await;
let np = store.notepad(&sid).unwrap();
assert_eq!(np[0].text, "a\nb\nc");
}
}
+25 -1
View File
@@ -147,9 +147,16 @@ impl ShellRequest {
.filter(|s| !s.trim().is_empty())
.ok_or_else(|| anyhow::anyhow!("shell_exec requires a non-empty 'command'"))?
.to_string();
let cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
let cwd = args
.get("cwd")
.and_then(|v| v.as_str())
.filter(|s| !s.trim().is_empty())
.map(str::to_string);
// Accept `timeout` as an alias of `timeout_secs`: the TOOL_USE manual
// spells `timeout?`, so a model following it must not be silently ignored.
let secs = args
.get("timeout_secs")
.or_else(|| args.get("timeout"))
.and_then(|v| v.as_u64())
.unwrap_or(DEFAULT_TIMEOUT_SECS)
.clamp(1, 3600);
@@ -268,4 +275,21 @@ mod tests {
assert_eq!(d["function"]["name"], "shell_exec");
assert_eq!(d["function"]["parameters"]["required"][0], "command");
}
#[test]
fn empty_cwd_falls_back_and_timeout_alias_accepted() {
// cwd:"" (or whitespace) must be None so the caller falls back to the
// session folder instead of Command::current_dir("") failing with ENOENT.
for cwd in ["", " "] {
let r = ShellRequest::from_args(&json!({"command":"ls","cwd":cwd})).unwrap();
assert_eq!(r.cwd, None, "cwd {cwd:?} should fall back");
}
// The manual spells `timeout`; accept it as an alias of timeout_secs.
let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300})).unwrap();
assert_eq!(r.timeout, Duration::from_secs(300));
// timeout_secs wins when both are present.
let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300,"timeout_secs":5}))
.unwrap();
assert_eq!(r.timeout, Duration::from_secs(5));
}
}
+3 -1
View File
@@ -65,8 +65,10 @@ pub trait Formatter: Send + Sync {
fn model_name(&self) -> &str;
/// The formatter's default token budget when the request sets none.
/// Matches the project-wide generation budget (CoT + answer share it); a
/// dialect with a real tokenizer overrides this from its config.
fn default_max_new(&self) -> u32 {
2048
16384
}
/// Token count of a text, used to route uploads (small-text inline threshold).
+104 -7
View File
@@ -122,31 +122,57 @@ impl AuthConfig {
.get(axum::http::header::HOST)
.and_then(|h| h.to_str().ok())
.unwrap_or("");
let host = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
self.allowed_hosts
.iter()
.any(|h| h.eq_ignore_ascii_case(host))
// Strip the port. A bracketed IPv6 Host (`[::1]:8095` or `[::1]`) must
// yield `::1`, not `[:` — rsplit_once(':') alone mangles it.
let host = match host.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or(v6),
None => host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host),
};
self.allowed_hosts.iter().any(|h| {
let h = h
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or(h);
h.eq_ignore_ascii_case(host)
})
}
fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool {
let Some(key) = self.api_key.as_deref() else {
// An empty/whitespace key is a misconfiguration, not "accept an empty
// header": treat it as no key rather than letting `Bearer ` pass.
let Some(key) = self.api_key.as_deref().filter(|k| !k.trim().is_empty()) else {
return true;
};
if let Some(auth) = headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
{
if auth.strip_prefix("Bearer ").is_some_and(|t| t == key) {
// The auth scheme is case-insensitive (RFC 9110); the token is not.
if auth
.get(..7)
.is_some_and(|p| p.eq_ignore_ascii_case("Bearer "))
&& ct_eq(&auth.as_bytes()[7..], key.as_bytes())
{
return true;
}
}
headers
.get("x-api-key")
.and_then(|v| v.to_str().ok())
.is_some_and(|k| k == key)
.is_some_and(|k| ct_eq(k.as_bytes(), key.as_bytes()))
}
}
/// Constant-time byte equality (no timing side-channel on the API key), std-only.
/// The length XOR is folded into the accumulator so unequal lengths still fail.
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
let mut diff = a.len() ^ b.len();
for (x, y) in a.iter().zip(b.iter()) {
diff |= usize::from(*x ^ *y);
}
diff == 0
}
/// Enforces the Host allowlist and (except on `/health`) the API key before any
/// handler runs.
async fn auth_middleware(
@@ -362,3 +388,74 @@ async fn json_body<T: DeserializeOwned>(req: axum::extract::Request) -> Result<T
serde_json::from_slice::<T>(&bytes)
.map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::{HeaderMap, HeaderName};
fn host_header(value: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(axum::http::header::HOST, value.parse().unwrap());
h
}
#[test]
fn host_allowlist_parses_ipv6_and_ports() {
let auth = AuthConfig {
api_key: None,
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
};
assert!(auth.host_allowed(&host_header("localhost:8095")));
assert!(auth.host_allowed(&host_header("127.0.0.1:8095")));
assert!(auth.host_allowed(&host_header("[::1]:8095")));
assert!(auth.host_allowed(&host_header("[::1]")));
assert!(!auth.host_allowed(&host_header("evil.com:8095")));
let open = AuthConfig {
api_key: None,
allowed_hosts: vec!["*".into()],
};
assert!(open.host_allowed(&host_header("anything.example")));
}
#[test]
fn key_check_bearer_case_and_empty_key() {
let auth = AuthConfig {
api_key: Some("secret".into()),
allowed_hosts: vec![],
};
let bearer = |v: &str| {
let mut h = HeaderMap::new();
h.insert(axum::http::header::AUTHORIZATION, v.parse().unwrap());
h
};
assert!(auth.key_ok(&bearer("Bearer secret")));
// RFC 9110: the auth scheme is case-insensitive.
assert!(auth.key_ok(&bearer("bearer secret")));
assert!(auth.key_ok(&bearer("BEARER secret")));
assert!(!auth.key_ok(&bearer("Bearer nope")));
let mut x = HeaderMap::new();
x.insert(
HeaderName::from_static("x-api-key"),
"secret".parse().unwrap(),
);
assert!(auth.key_ok(&x));
// An empty configured key is a misconfiguration -> treated as no auth,
// never "accept an empty Bearer/x-api-key header".
let empty = AuthConfig {
api_key: Some("".into()),
allowed_hosts: vec![],
};
assert!(empty.key_ok(&HeaderMap::new()));
assert!(empty.key_ok(&bearer("Bearer ")));
}
#[test]
fn ct_eq_compares_bytes_without_early_exit() {
assert!(ct_eq(b"secret", b"secret"));
assert!(ct_eq(b"", b""));
assert!(!ct_eq(b"secret", b"secreu"));
assert!(!ct_eq(b"secret", b"secret2"));
assert!(!ct_eq(b"", b"x"));
}
}
+19
View File
@@ -77,6 +77,11 @@ pub struct Config {
/// launcher's monkey-patch).
#[serde(default)]
pub reasoning_effort: Option<String>,
/// Default generation budget (`max_new` tokens) when neither the request nor
/// the session sets one. Reasoning + answer share it; the default is raised
/// (16384) so chain-of-thought is not truncated mid-reasoning at the old 2048.
#[serde(default)]
pub max_new: Option<u32>,
#[serde(default)]
pub sampling: SamplingDefaults,
@@ -263,6 +268,12 @@ impl Config {
self.language.clone().unwrap_or_else(|| "it".to_string())
}
/// Effective default generation budget: config `max_new` > 16384. This is the
/// ceiling on reasoning + answer tokens when a request/session sets none.
pub fn max_new_default(&self) -> u32 {
self.max_new.unwrap_or(16384)
}
/// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> {
@@ -395,6 +406,14 @@ mod tests {
assert_eq!(keys, " temperature=1.0");
}
#[test]
fn max_new_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
assert_eq!(cfg.max_new_default(), 16384); // absent -> raised default
let cfg2 = Config::parse(r#"{"exe":"/x/e","max_new":8192}"#, "test").unwrap();
assert_eq!(cfg2.max_new_default(), 8192);
}
#[test]
fn timeouts_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
+95 -7
View File
@@ -103,7 +103,19 @@ fn prefix_messages(
// Tool/system turns stay untagged. Strip any tag the model echoed into
// stored content so we never stack a second one (duplication loop).
let clean = strip_speaker_tags(&m.content);
let content = match m.role.as_str() {
let tool_calls = m
.tool_calls_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
// A tool-call-only assistant turn carries no text: keep content None to
// match `agent::run_loop` (which pushed the model's message verbatim).
// Stamping a bare [SPEAKER] here would emit a spurious <|content_text|>
// block, priming empty speaker tags and diverging from the cached prefix.
let tool_only = m.role == "assistant" && clean.is_empty() && tool_calls.is_some();
let content = if tool_only {
None
} else {
let text = match m.role.as_str() {
"user" => format!(
"{}{}",
speaker_prefix(user_name, m.created_at, tz_offset),
@@ -116,12 +128,18 @@ fn prefix_messages(
),
_ => clean,
};
let mut msg = text_message(role_of(&m.role), content);
msg.tool_calls = m
.tool_calls_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
Some(serde_json::Value::String(text))
};
messages.push(ChatMessage {
role: role_of(&m.role),
content,
// Restore the tool-call id so the template resolves the tool name from
// the preceding assistant turn (and the prefix matches run_loop).
tool_call_id: m.tool_call_id.clone(),
tool_calls,
name: None,
reasoning_content: None,
});
}
messages
}
@@ -326,6 +344,76 @@ mod tests {
);
}
#[test]
fn history_restores_tool_call_id_and_skips_speaker_on_tool_only_turns() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: crate::store::SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let calls = serde_json::json!([{
"id": "call_1", "type": "function",
"function": {"name": "shell_exec", "arguments": "{\"command\":\"ls\"}"}
}]);
let history = vec![
StoredMessage {
id: 1,
role: "user".into(),
content: "lista i file".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_700_000_000,
},
StoredMessage {
id: 2,
role: "assistant".into(),
content: "".into(),
reasoning_content: Some("penso".into()),
tool_calls_json: Some(calls.to_string()),
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_700_000_001,
},
StoredMessage {
id: 3,
role: "tool".into(),
content: "file.txt".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: Some("call_1".into()),
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_700_000_002,
},
];
let prefix = compose_prefix(&sess, &history, "Federico", &[], &[]);
// BUG-05: the tool-only assistant turn has no text (no bare [SPEAKER] block).
let asst = prefix
.iter()
.find(|m| matches!(m.role, Role::Assistant))
.unwrap();
assert!(
asst.content.is_none(),
"tool-only turn must not carry a [SPEAKER] text block"
);
assert!(asst.tool_calls.is_some());
// BUG-04: the tool result keeps its id so the template resolves the name.
let tool = prefix
.iter()
.find(|m| matches!(m.role, Role::Tool))
.unwrap();
assert_eq!(tool.tool_call_id.as_deref(), Some("call_1"));
}
#[test]
fn format_stamp_known_dates_and_offset() {
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
+12 -2
View File
@@ -163,6 +163,8 @@ pub struct InklingDialect {
think_acc: String,
end_ws: String,
emitted_visible: bool,
/// Thinking already streamed live by `emit` (so `finish` must not re-emit it).
emitted_reasoning: bool,
/// How many tool frames have been rendered (diagnostics).
pub calls: u32,
}
@@ -228,6 +230,7 @@ impl InklingDialect {
State::Think => {
self.append_think(chunk);
out.push(Out::reasoning(chunk));
self.emitted_reasoning = true;
}
State::ThinkEnd => {
if chunk.trim().is_empty() {
@@ -237,6 +240,7 @@ impl InklingDialect {
let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk);
self.append_think(&combined);
out.push(Out::reasoning(combined));
self.emitted_reasoning = true;
self.end_ws.clear();
self.state = State::Think;
}
@@ -318,6 +322,10 @@ impl InklingDialect {
State::ThinkEnd => {
let held = format!("{}{}", tag::END_MESSAGE, self.end_ws);
self.append_think(&held);
// Stream the quoted end-message live (mirrors TextEnd below):
// it is thinking text, not a channel end, and must not be lost.
out.push(Out::reasoning(held));
self.emitted_reasoning = true;
self.end_ws.clear();
}
State::Text => {
@@ -424,11 +432,13 @@ impl InklingDialect {
self.emitted_visible = true;
}
}
// #6682: budget expired inside thinking with no visible answer yet:
// surface the truncated thinking rather than an empty 200 OK.
// #6682: budget expired inside thinking with no visible answer yet.
// Thinking is streamed live by `emit`, so only surface the buffer if
// it was somehow NOT streamed — never duplicate the live CoT (BUG-06).
State::Think | State::ThinkEnd
if reason == Some("length")
&& !self.emitted_visible
&& !self.emitted_reasoning
&& !think.trim().is_empty() =>
{
out.push(Out::reasoning(think));
+9 -1
View File
@@ -40,11 +40,19 @@ impl InklingFormatter {
template,
model,
effort,
max_new_default: 2048,
max_new_default: 16384,
default_sampling,
}
}
/// Override the default generation budget (config `max_new`). Reasoning and
/// answer share this ceiling; the model still stops early at EOS, so a larger
/// budget only matters when it would otherwise be truncated mid-reasoning.
pub fn with_max_new(mut self, n: u32) -> Self {
self.max_new_default = n;
self
}
/// OpenAI messages -> the JSON the template expects, normalizing the newer
/// `developer` role to `system` (the template's role map has no developer).
fn messages_json(req: &ChatRequest) -> Json {
+138 -8
View File
@@ -132,7 +132,11 @@ pub fn materialize(sources: &[String]) -> Result<Vec<PathBuf>, ImageError> {
/// Bytes of one source: base64 data URL, http(s) fetch, or local file path.
fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
if let Some(rest) = src.strip_prefix("data:") {
if src
.get(..5)
.is_some_and(|s| s.eq_ignore_ascii_case("data:"))
{
let rest = &src[5..];
let (meta, data) = rest
.split_once(',')
.ok_or_else(|| ImageError::Unsupported("malformed data URL".into()))?;
@@ -141,15 +145,63 @@ fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
"only base64 data URLs are supported".into(),
));
}
// Cap the encoded length BEFORE decoding: base64 inflates ~4/3, so a
// giant data URL must not allocate gigabytes (OOM DoS).
if data.len() as u64 > MAX_IMAGE_BYTES * 4 / 3 + 16 {
return Err(ImageError::Decode(
"data URL exceeds the image size cap".into(),
));
}
return base64::engine::general_purpose::STANDARD
.decode(data)
.map_err(|e| ImageError::Decode(e.to_string()));
}
if src.starts_with("http://") || src.starts_with("https://") {
// Scheme match is case-insensitive: `HTTP://…` must fetch (through the SSRF
// guard), not fall through to a local file read.
let is_http = src
.get(..7)
.is_some_and(|s| s.eq_ignore_ascii_case("http://"))
|| src
.get(..8)
.is_some_and(|s| s.eq_ignore_ascii_case("https://"));
if is_http {
return fetch_http(src);
}
let path = src.strip_prefix("file://").unwrap_or(src);
std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))
let path = if src
.get(..7)
.is_some_and(|s| s.eq_ignore_ascii_case("file://"))
{
&src[7..]
} else {
src
};
// Same fd for check and read (no TOCTOU symlink swap); only regular files,
// size-bounded: a device (`/dev/zero`) would exhaust memory, a multi-GB file
// would OOM. `take` caps the read even if the file grows between check/read.
let file = std::fs::File::open(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
let meta = file
.metadata()
.map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
if !meta.is_file() {
return Err(ImageError::Unsupported(format!(
"{path}: not a regular file"
)));
}
if meta.len() > MAX_IMAGE_BYTES {
return Err(ImageError::Decode(format!(
"{path}: exceeds the image size cap"
)));
}
let mut buf = Vec::new();
file.take(MAX_IMAGE_BYTES + 1)
.read_to_end(&mut buf)
.map_err(|e| ImageError::Io(format!("{path}: {e}")))?;
if buf.len() as u64 > MAX_IMAGE_BYTES {
return Err(ImageError::Decode(format!(
"{path}: exceeds the image size cap"
)));
}
Ok(buf)
}
/// Fetch an http(s) image with a timeout and a size cap. Blocks literal
@@ -163,6 +215,9 @@ fn fetch_http(src: &str) -> Result<Vec<u8>, ImageError> {
}
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(FETCH_TIMEOUT))
// Do not follow redirects: a 3xx to an internal host (169.254.169.254,
// 127.0.0.1) would bypass the lexical SSRF guard on the initial URL.
.max_redirects(0)
.build()
.new_agent();
let mut resp = agent
@@ -192,18 +247,47 @@ fn is_blocked_host(url: &str) -> bool {
None => host.split(':').next().unwrap_or(host), // host:port
};
let host = host.to_ascii_lowercase();
// A trailing FQDN dot (`localhost.`) is the same host: strip it.
let host = host.trim_end_matches('.');
if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") {
return true;
}
match host.parse::<std::net::IpAddr>() {
Ok(std::net::IpAddr::V4(v4)) => {
v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
}
Ok(std::net::IpAddr::V6(v6)) => v6.is_loopback() || v6.is_unspecified(),
Ok(std::net::IpAddr::V4(v4)) => is_non_global_v4(v4),
Ok(std::net::IpAddr::V6(v6)) => is_non_global_v6(v6),
Err(_) => false,
}
}
/// IPv4 addresses that are not globally routable: loopback, private, link-local,
/// unspecified, broadcast, multicast, 0/8 "this network", and CGNAT 100.64/10
/// (used by Tailscale).
fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
let o = v4.octets();
v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_unspecified()
|| v4.is_broadcast()
|| v4.is_multicast()
|| o[0] == 0
|| (o[0] == 100 && (o[1] & 0xc0) == 64) // 100.64.0.0/10 CGNAT
}
/// IPv6 non-global addresses, judging IPv4-mapped (`::ffff:a.b.c.d`) by their
/// IPv4 target so `http://[::ffff:127.0.0.1]/` cannot slip past the guard.
fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
if let Some(v4) = v6.to_ipv4_mapped() {
return is_non_global_v4(v4);
}
let seg = v6.segments();
v6.is_loopback()
|| v6.is_unspecified()
|| (seg[0] & 0xfe00) == 0xfc00 // fc00::/7 ULA
|| (seg[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local
|| (seg[0] & 0xff00) == 0xff00 // ff00::/8 multicast
}
/// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate.
fn normalize(data: Vec<u8>) -> Result<(Vec<u8>, &'static str), ImageError> {
if let Some(ext) = sniff(&data) {
@@ -246,6 +330,7 @@ mod tests {
"http://[::1]/x.png",
"http://user@127.0.0.1/x.png",
"http://foo.local/x.png",
"http://localhost./x.png",
] {
assert!(is_blocked_host(url), "{url} should be blocked");
}
@@ -253,4 +338,49 @@ mod tests {
assert!(!is_blocked_host(url), "{url} should be allowed");
}
}
#[test]
fn ssrf_guard_blocks_mapped_ula_cgnat() {
for url in [
"http://[::ffff:127.0.0.1]/x.png",
"http://[::ffff:10.0.0.1]/x.png",
"http://[::ffff:169.254.169.254]/x.png",
"http://[fc00::1]/x.png",
"http://[fe80::1]/x.png",
"http://100.64.0.1/x.png",
"http://224.0.0.1/x.png",
"http://255.255.255.255/x.png",
] {
assert!(is_blocked_host(url), "{url} should be blocked");
}
// A globally routable IPv4-mapped address is still allowed.
assert!(!is_blocked_host("http://[::ffff:8.8.8.8]/x.png"));
}
#[test]
fn http_scheme_is_case_insensitive() {
assert!(is_blocked_host("HTTP://127.0.0.1/x.png"));
// load_bytes routes HTTP:// through fetch_http (which refuses loopback),
// not through a local file read.
let err = load_bytes("HTTP://127.0.0.1/x.png").unwrap_err();
assert!(matches!(err, ImageError::Fetch(_)), "{err:?}");
}
#[test]
fn oversized_data_url_is_refused_before_decode() {
let big = "A".repeat((MAX_IMAGE_BYTES * 4 / 3 + 17) as usize);
let src = format!("data:image/png;base64,{big}");
let err = load_bytes(&src).unwrap_err();
assert!(matches!(err, ImageError::Decode(_)), "{err:?}");
}
#[test]
fn non_regular_file_is_refused() {
// /dev/zero is a char device: refused before reading (std::fs::read would
// otherwise allocate until OOM). Guarded for non-Unix hosts.
if std::path::Path::new("/dev/zero").exists() {
let err = load_bytes("/dev/zero").unwrap_err();
assert!(matches!(err, ImageError::Unsupported(_)), "{err:?}");
}
}
}
+9 -2
View File
@@ -133,8 +133,15 @@ impl Detok {
/// Flush whatever is left (including any held replacement) at end of stream.
pub fn finish(&mut self) -> String {
let full = self.tok.decode_all(&self.ids).unwrap_or_default();
if full.len() > self.emitted {
let piece = full[self.emitted..].to_string();
// `emitted` was a char boundary in an earlier decode; floor it to one in
// case the suffix re-aligned (an incomplete code point resolved at EOF),
// so the slice can never panic.
let mut start = self.emitted.min(full.len());
while start > 0 && !full.is_char_boundary(start) {
start -= 1;
}
if full.len() > start {
let piece = full[start..].to_string();
self.emitted = full.len();
piece
} else {
+6 -2
View File
@@ -144,13 +144,16 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
return ExitCode::FAILURE;
}
};
let fmt = Arc::new(InklingFormatter::new(
let fmt = Arc::new(
InklingFormatter::new(
tok,
template,
cfg.model_name().to_string(),
cfg.reasoning_effort.clone(),
cfg.sampling.to_sampling(),
));
)
.with_max_new(cfg.max_new_default()),
);
let engine = match Engine::start(
&cfg.exe,
@@ -252,6 +255,7 @@ fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_
"reasoning_effort: {}",
cfg.reasoning_effort.as_deref().unwrap_or("(default)")
);
println!("max_new (generation budget): {}", cfg.max_new_default());
println!(
"sampling: temp={:?} top_p={:?} min_p={:?} rep_pen={:?}",
cfg.sampling.temperature,
+58 -4
View File
@@ -62,11 +62,22 @@ pub fn markdown_to_safe_html(text: &str) -> String {
}
/// Render a LaTeX fragment to MathML. `display` selects block (`$$…$$`) vs inline
/// (`$…$`) mode. On the rare writer error we fall back to escaped source in a
/// `<code>` so nothing is lost; invalid LaTeX is flagged inline by the crate.
/// (`$…$`) mode. Invalid LaTeX falls back to escaped source in a `<code>`.
///
/// Safety: `pulldown-latex` renders a parse error as
/// `<merror><mtext>…raw source window…</mtext></merror>` and does NOT escape that
/// window (its `Err` branch writes `e.to_string()` verbatim, unlike normal text).
/// `<mtext>` is an HTML text integration point, so a crafted malformed fragment
/// can smuggle a live `<img>`/`<svg>` into `innerHTML` (stored XSS). Writing to a
/// `String` never fails, so `push_mathml` returns `Ok` even on a parse error — the
/// writer-error fallback below would never fire. We therefore collect the events
/// first and fall back to escaped source on ANY parse error.
fn render_math(latex: &str, display: bool) -> String {
let storage = Storage::new();
let parser = pulldown_latex::Parser::new(latex, &storage);
let events: Result<Vec<_>, _> = pulldown_latex::Parser::new(latex, &storage).collect();
let Ok(events) = events else {
return format!("<code>{}</code>", escape_html(latex));
};
let config = RenderConfig {
display_mode: if display {
DisplayMode::Block
@@ -76,7 +87,8 @@ fn render_math(latex: &str, display: bool) -> String {
..RenderConfig::default()
};
let mut out = String::new();
match push_mathml(&mut out, parser, config) {
let events = events.into_iter().map(Ok::<_, std::convert::Infallible>);
match push_mathml(&mut out, events, config) {
Ok(()) => out,
Err(_) => format!("<code>{}</code>", escape_html(latex)),
}
@@ -89,6 +101,17 @@ fn render_math(latex: &str, display: bool) -> String {
fn safe_url(url: &str) -> String {
let cleaned: String = url.chars().filter(|c| !c.is_control()).collect();
let trimmed = cleaned.trim();
// Protocol-relative URLs (`//host/…`) inherit the page scheme and can point
// off-origin: block them so a model-written image/link cannot beacon to an
// attacker host. The WHATWG URL parser also treats `\\`, `/\`, `\/` as
// scheme-relative on http(s) pages, so block those spellings too.
if trimmed.starts_with("//")
|| trimmed.starts_with("\\\\")
|| trimmed.starts_with("/\\")
|| trimmed.starts_with("\\/")
{
return String::new();
}
if let Some(colon) = trimmed.find(':') {
let scheme = &trimmed[..colon];
let looks_like_scheme = scheme
@@ -207,5 +230,36 @@ mod tests {
assert_eq!(safe_url("data:text/html,x"), "");
assert_eq!(safe_url("vbscript:x"), "");
assert_eq!(safe_url("file:///etc/passwd"), "");
// Protocol-relative URLs are blocked (off-origin beacon / hijacking),
// including the backslash spellings the WHATWG parser normalizes.
assert_eq!(safe_url("//evil.com/pixel.png"), "");
assert_eq!(safe_url("//evil.com"), "");
assert_eq!(safe_url("\\\\evil.com"), "");
assert_eq!(safe_url("/\\evil.com"), "");
assert_eq!(safe_url("\\/evil.com"), "");
}
#[test]
fn malformed_latex_math_cannot_inject_live_html() {
// pulldown-latex writes the raw source window of a parse error into
// <mtext> unescaped; <mtext> is an HTML integration point. These must
// fall back to escaped <code>, never a live <img>/<svg> or <merror>.
for src in [
"$<img/src=1 onerror=alert(1)#$",
"$$#<svg onload=alert(1)>#$$",
"$\\frac{<img src=x onerror=alert(2)>}{#}$",
] {
let html = markdown_to_safe_html(src);
assert!(!html.contains("<img"), "live img leaked: {html}");
assert!(!html.contains("<svg"), "live svg leaked: {html}");
assert!(!html.contains("<merror"), "raw error window leaked: {html}");
assert!(html.contains("<code>"), "expected escaped fallback: {html}");
}
}
#[test]
fn protocol_relative_image_is_stripped() {
let html = markdown_to_safe_html("![x](//evil.com/pixel.png)");
assert!(!html.contains("//evil.com"), "{html}");
}
}
+47 -2
View File
@@ -346,6 +346,9 @@ impl SqliteStore {
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.pragma_update(None, "foreign_keys", "ON")?;
// Wait briefly for a concurrent writer (e.g. an external reader/tool in
// WAL) instead of failing immediately with SQLITE_BUSY.
conn.pragma_update(None, "busy_timeout", 5000)?;
conn.execute_batch(SCHEMA)?;
migrate(&conn)?;
seed_context_sections(&conn)?;
@@ -637,13 +640,16 @@ impl Store for SqliteStore {
fn stats(&self) -> Result<Stats> {
let conn = self.lock();
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
// Totals + tool-call count in one pass. tool_calls_json is always a JSON
// array of calls (or NULL); json_array_length counts the calls themselves.
// Totals + tool-call count in one pass. tool_calls_json is a JSON array
// of calls (or NULL); guard with json_valid/json_type so one corrupt or
// non-array row cannot fail the whole stats query.
let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row(
"SELECT COUNT(*),
COALESCE(SUM(prompt_tokens),0),
COALESCE(SUM(completion_tokens),0),
COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL
AND json_valid(tool_calls_json)
AND json_type(tool_calls_json) = 'array'
THEN json_array_length(tool_calls_json) ELSE 0 END),0)
FROM messages",
[],
@@ -975,6 +981,45 @@ mod tests {
assert_eq!(st.daily[0].completion_tokens, 5);
}
#[test]
fn stats_survives_a_corrupt_tool_calls_row() {
let s = store();
let sess = s
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
// A corrupt (non-JSON) tool_calls_json row must not fail the whole query.
s.append_message(
&sess.id,
NewMessage {
role: "assistant",
content: "x",
reasoning_content: None,
tool_calls_json: Some("not-json"),
tool_call_id: None,
prompt_tokens: 1,
completion_tokens: 1,
},
)
.unwrap();
// A valid array still counts.
s.append_message(
&sess.id,
NewMessage {
role: "assistant",
content: "y",
reasoning_content: None,
tool_calls_json: Some(r#"[{"id":"1"}]"#),
tool_call_id: None,
prompt_tokens: 1,
completion_tokens: 1,
},
)
.unwrap();
let st = s.stats().unwrap();
assert_eq!(st.messages, 2);
assert_eq!(st.tool_calls, 1); // corrupt row skipped, valid array counted
}
#[test]
fn settings_instance_and_name_lock() {
let s = store();
+31 -4
View File
@@ -214,7 +214,9 @@ fn truncated_tool_falls_back_to_header_name() {
#[test]
fn thinking_only_at_length_surfaces_reasoning() {
// #6682: budget expires mid-thinking with no answer.
// #6682: budget expires mid-thinking with no answer. Thinking is streamed
// live by emit(), so finish() must NOT re-emit it: the whole CoT appears
// exactly once (BUG-06 — duplication was amplified by the 16384 budget).
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
@@ -224,9 +226,34 @@ fn thinking_only_at_length_surfaces_reasoning() {
Some("length"),
);
assert!(content_of(&outs).is_empty());
// the live delta plus the finish-time accumulation both carry it (faithful
// to the reference: patched emit + _finish_typed #6682)
assert!(reasoning_of(&outs).contains("pondering"));
assert_eq!(
reasoning_of(&outs),
"pondering",
"thinking must appear exactly once, not duplicated at finish"
);
}
#[test]
fn quoted_end_message_in_think_end_streams_live() {
// #6675: two consecutive end-messages in thinking — the first is quoted text
// and must surface in reasoning live (mirrors TextEnd), not be lost.
let outs = run(
&[
(tag::MESSAGE_MODEL, true),
(tag::CONTENT_THINKING, true),
("x", false),
(tag::END_MESSAGE, true),
(tag::END_MESSAGE, true),
],
None,
);
let r = reasoning_of(&outs);
assert!(r.contains('x'), "{r}");
assert!(
r.contains(tag::END_MESSAGE),
"quoted tag must stream live: {r}"
);
assert!(content_of(&outs).is_empty());
}
#[test]
+15 -1
View File
@@ -86,7 +86,7 @@ fn build_prompt_renders_and_encodes() {
assert!(prompt.ids.contains(&text_id));
assert!(prompt.ids.contains(&2)); // "hello"
assert!(prompt.ids.contains(&end_id));
assert_eq!(prompt.max_new, 2048); // default
assert_eq!(prompt.max_new, 16384); // default (raised so CoT is not truncated)
let _ = std::fs::remove_file(&path);
}
@@ -144,6 +144,20 @@ fn max_tokens_override_is_honored() {
let _ = std::fs::remove_file(&path);
}
#[test]
fn with_max_new_overrides_default_budget() {
let (fmt, _tok, path) = formatter();
assert_eq!(fmt.default_max_new(), 16384);
let fmt = fmt.with_max_new(8192);
assert_eq!(fmt.default_max_new(), 8192);
let req: ChatRequest = serde_json::from_value(
json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}),
)
.unwrap();
assert_eq!(fmt.build_prompt(&req).unwrap().max_new, 8192);
let _ = std::fs::remove_file(&path);
}
#[test]
fn decoder_emits_structured_tool_call() {
let (fmt, tok, path) = formatter();