Compare commits

..
Author SHA1 Message Date
Watch dad6b9780c test(runtime): give bash unit tests a realistic timeout on slow Windows ARM runners
- Increased timeout from 1_000ms to 30_000ms in executes_simple_command,
  disables_sandbox_when_requested, and prevents_stdin_hangs_by_redirecting_to_null
  tests to account for git-bash cold start delays on Windows ARM runners
- Added clear error message to executes_simple_command assertion that includes
  stderr for better debugging of future timeout failures
- Fixes CI flake: ultraworkers/claw-code ca875261 run 45476362842 and 578e910b run 45815130318
2026-11-26 12:57:33 +00:00
13 changed files with 53 additions and 540 deletions

No files matched your search

-25
View File
@@ -5,31 +5,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.16] - 2026-11-27
### Fixed
- Hooks no longer fail with BrokenPipe when a hook exits without reading a stdin payload larger than the pipe buffer (#3410)
## [0.1.15] - 2026-11-27
### Added
- Outbound extra-headers hook for AnthropicClient, OpenAiCompatClient, and ProviderClient to add custom headers to model requests (#3407)
### Changed
- Documentation: document WorldRouter OpenAI-compatible gateway setup (d53a0882)
- Documentation: document onomeo OpenAI-compatible gateway setup (#3399)
- Documentation: document Straitly OpenAI-compatible gateway setup (#3400)
- Documentation: document TeamoRouter OpenAI-compatible gateway setup (#3402)
- Documentation: document TrustedRouter OpenAI-compatible gateway setup (#3403)
- Documentation: rename UberLLM to MartLLM in gateway setup documentation (#3405)
### Internal/Tests
- Windows ARM64 bash test timeout hardening (#3406)
## [0.1.14] - 2026-11-23
### Fixed
-10
View File
@@ -592,16 +592,6 @@ Runtime config is loaded in this order, with later entries overriding earlier on
The list is also the precedence chain: project-local settings override project settings, project settings override the legacy project `.claw.json`, and project files override user files. `claw --output-format json config` includes each discovered file's `precedence_rank`, `wins_for_keys`, and `shadowed_keys` so automation can see which file controls each effective key without reimplementing the merge order.
### Untrusted project settings
Project-local config files (`.claw.json`, `.claw/settings.json`) are loaded from the repository and are not individually approved by the user. To prevent accidental or malicious escalation of privileges, `claw` strips the following settings from project-local files:
- **Hooks** (`hooks.*`): Project hooks are always stripped. User and local settings (`.claw/settings.local.json`) may define hooks.
- **Permission grants** (`permissions.allow`, `permissions.defaultMode`, legacy top-level `permissionMode`): Project files cannot grant elevated permissions. User and local settings may set these.
- **Permission restrictions** (`permissions.deny`, `permissions.ask`) remain active from project files, as they only limit access.
When a project file attempts to use stripped settings, a warning is emitted: `Ignoring project <setting> in <path> because project trust approval is not supported.` To configure permissions for a repository, place settings in `~/.claw/settings.json` (user-level) or `.claw/settings.local.json` (local-only, typically gitignored).
## MCP server validation
`claw mcp --output-format json` loads valid `mcpServers` entries even when sibling entries are malformed. The JSON list envelope distinguishes the total configured entries from the valid and invalid subsets:
+11 -11
View File
@@ -93,7 +93,7 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "api"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"criterion",
"reqwest",
@@ -478,7 +478,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "claw-analog"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"api",
"clap",
@@ -498,7 +498,7 @@ dependencies = [
[[package]]
name = "claw-rag-service"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"axum 0.8.9",
"blake3",
@@ -531,7 +531,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "commands"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"plugins",
"runtime",
@@ -540,7 +540,7 @@ dependencies = [
[[package]]
name = "compat-harness"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"commands",
"runtime",
@@ -1568,7 +1568,7 @@ dependencies = [
[[package]]
name = "mock-anthropic-service"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"api",
"serde_json",
@@ -1761,7 +1761,7 @@ dependencies = [
[[package]]
name = "plugins"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"serde",
"serde_json",
@@ -2136,7 +2136,7 @@ dependencies = [
[[package]]
name = "runtime"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"getrandom 0.2.17",
"glob",
@@ -2263,7 +2263,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "rusty-claude-cli"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"api",
"commands",
@@ -2624,7 +2624,7 @@ dependencies = [
[[package]]
name = "telemetry"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"serde",
"serde_json",
@@ -2904,7 +2904,7 @@ dependencies = [
[[package]]
name = "tools"
version = "0.1.16"
version = "0.1.14"
dependencies = [
"api",
"aspect-core",
+1 -1
View File
@@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "2"
[workspace.package]
version = "0.1.16"
version = "0.1.14"
edition = "2021"
license = "MIT"
publish = false
-16
View File
@@ -1,5 +1,4 @@
use crate::error::ApiError;
use crate::extra_headers::ExtraHeadersHook;
use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats};
use crate::providers::anthropic::{self, AnthropicClient, AuthSource};
use crate::providers::openai_compat::{self, OpenAiCompatClient, OpenAiCompatConfig};
@@ -201,21 +200,6 @@ impl ProviderClient {
}
}
/// Install a provider that may add outbound headers to each model request.
///
/// Applies to every provider variant. Without a provider the request is
/// unchanged.
#[must_use]
pub fn with_extra_headers_provider(self, provider: ExtraHeadersHook) -> Self {
match self {
Self::Anthropic(client) => {
Self::Anthropic(client.with_extra_headers_provider(provider))
}
Self::Xai(client) => Self::Xai(client.with_extra_headers_provider(provider)),
Self::OpenAi(client) => Self::OpenAi(client.with_extra_headers_provider(provider)),
}
}
#[must_use]
pub fn prompt_cache_stats(&self) -> Option<PromptCacheStats> {
match self {
-150
View File
@@ -1,150 +0,0 @@
//! Optional outbound HTTP header provider for model requests.
//!
//! Some hosts must annotate each model request with routing, quota, or
//! cache-affinity metadata that only the caller can compute. A client opts in
//! with [`crate::providers::anthropic::AnthropicClient::with_extra_headers_provider`]
//! or [`crate::providers::openai_compat::OpenAiCompatClient::with_extra_headers_provider`];
//! clients without a provider send byte-for-byte the same headers as before.
//!
//! The provider runs in-process and receives the exact JSON body that is about
//! to be sent. It must treat the body as read-only: the hook can only add
//! headers, never change the payload.
use std::fmt;
use std::sync::Arc;
use reqwest::header::{HeaderName, HeaderValue};
use reqwest::RequestBuilder;
use serde_json::Value;
/// Facts the host may use when deriving headers.
pub struct ExtraHeadersContext<'a> {
/// Provider label reported by the client (`"Anthropic"`, `"OpenAI"`, ...).
pub provider: &'a str,
/// Model id as it appears in the request body.
pub model: &'a str,
/// The JSON body that will be sent with this request. Read-only.
pub body: &'a Value,
}
/// Returns `(name, value)` pairs to add to one outbound request.
pub type ExtraHeadersProvider =
dyn Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync;
/// Headers owned by the transport. A provider cannot override them.
const RESERVED_HEADERS: &[&str] = &[
"accept",
"accept-encoding",
"anthropic-beta",
"anthropic-version",
"authorization",
"connection",
"content-length",
"content-type",
"host",
"transfer-encoding",
"user-agent",
"x-api-key",
];
/// A header provider attached to one client.
///
/// Cloning a client shares the provider; the closure must be `Send + Sync`.
#[derive(Clone)]
pub struct ExtraHeadersHook {
provider: Arc<ExtraHeadersProvider>,
}
impl ExtraHeadersHook {
#[must_use]
pub fn new(
provider: impl Fn(&ExtraHeadersContext<'_>) -> Vec<(String, String)> + Send + Sync + 'static,
) -> Self {
Self {
provider: Arc::new(provider),
}
}
/// Adds the provider's headers to one outbound model request.
///
/// Invalid names or values, and headers the transport owns, are dropped: a
/// broken provider must never fail a model call or rewrite credentials.
pub fn apply(
&self,
mut builder: RequestBuilder,
context: &ExtraHeadersContext<'_>,
) -> RequestBuilder {
for (name, value) in (self.provider)(context) {
let Ok(name) = HeaderName::from_bytes(name.as_bytes()) else {
continue;
};
if RESERVED_HEADERS.contains(&name.as_str()) {
continue;
}
let Ok(value) = HeaderValue::from_str(&value) else {
continue;
};
builder = builder.header(name, value);
}
builder
}
}
impl fmt::Debug for ExtraHeadersHook {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExtraHeadersHook").finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn context<'a>(body: &'a Value) -> ExtraHeadersContext<'a> {
ExtraHeadersContext {
provider: "Anthropic",
model: "claude-sonnet-4",
body,
}
}
#[test]
fn apply_keeps_valid_headers_and_drops_the_rest() {
let body = json!({"messages": []});
let hook = ExtraHeadersHook::new(|ctx: &ExtraHeadersContext<'_>| {
vec![
(
"x-route".to_string(),
format!("{}/{}", ctx.provider, ctx.model),
),
("authorization".to_string(), "Bearer nope".to_string()),
("anthropic-version".to_string(), "2099-01-01".to_string()),
("anthropic-beta".to_string(), "none".to_string()),
("bad header".to_string(), "dropped".to_string()),
("x-blank".to_string(), "bad\r\nvalue".to_string()),
]
});
let request = hook
.apply(
reqwest::Client::new().post("http://127.0.0.1/"),
&context(&body),
)
.build()
.expect("request builds");
assert_eq!(
request
.headers()
.get("x-route")
.and_then(|value| value.to_str().ok()),
Some("Anthropic/claude-sonnet-4")
);
assert!(request.headers().get("authorization").is_none());
assert!(request.headers().get("anthropic-version").is_none());
assert!(request.headers().get("anthropic-beta").is_none());
assert!(request.headers().get("bad header").is_none());
assert!(request.headers().get("x-blank").is_none());
}
}
-2
View File
@@ -1,7 +1,6 @@
mod client;
mod error;
mod extra_headers;
mod http_client;
mod prompt_cache;
mod providers;
@@ -14,7 +13,6 @@ pub use client::{
ProviderConfigKind,
};
pub use error::ApiError;
pub use extra_headers::{ExtraHeadersContext, ExtraHeadersHook, ExtraHeadersProvider};
pub use http_client::{
build_http_client, build_http_client_or_default, build_http_client_with,
build_http_client_with_opts, ProxyConfig, TimeoutConfig,
+2 -81
View File
@@ -13,7 +13,6 @@ use serde_json::{Map, Value};
use telemetry::{AnalyticsEvent, AnthropicRequestProfile, ClientIdentity, SessionTracer};
use crate::error::ApiError;
use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook};
use crate::http_client::build_http_client_or_default;
use crate::prompt_cache::{PromptCache, PromptCacheRecord, PromptCacheStats};
@@ -122,7 +121,6 @@ pub struct AnthropicClient {
request_profile: AnthropicRequestProfile,
session_tracer: Option<SessionTracer>,
prompt_cache: Option<PromptCache>,
extra_headers: Option<ExtraHeadersHook>,
last_prompt_cache_record: Arc<Mutex<Option<PromptCacheRecord>>>,
}
@@ -139,7 +137,6 @@ impl AnthropicClient {
request_profile: AnthropicRequestProfile::default(),
session_tracer: None,
prompt_cache: None,
extra_headers: None,
last_prompt_cache_record: Arc::new(Mutex::new(None)),
}
}
@@ -156,7 +153,6 @@ impl AnthropicClient {
request_profile: AnthropicRequestProfile::default(),
session_tracer: None,
prompt_cache: None,
extra_headers: None,
last_prompt_cache_record: Arc::new(Mutex::new(None)),
}
}
@@ -258,16 +254,6 @@ impl AnthropicClient {
self
}
/// Install a provider that may add outbound headers to each model request.
///
/// The provider sees the final JSON body and can only add headers. Only
/// real model requests reach it: `count_tokens` does not.
#[must_use]
pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self {
self.extra_headers = Some(provider);
self
}
#[must_use]
pub fn prompt_cache_stats(&self) -> Option<PromptCacheStats> {
self.prompt_cache.as_ref().map(PromptCache::stats)
@@ -502,17 +488,7 @@ impl AnthropicClient {
) -> Result<reqwest::Response, ApiError> {
let request_url = format!("{}/v1/messages", self.base_url.trim_end_matches('/'));
let request_body = render_standard_messages_body(&self.request_profile, request)?;
let mut request_builder = self.build_request(&request_url).json(&request_body);
if let Some(extra_headers) = &self.extra_headers {
request_builder = extra_headers.apply(
request_builder,
&ExtraHeadersContext {
provider: "Anthropic",
model: &request.model,
body: &request_body,
},
);
}
let request_builder = self.build_request(&request_url).json(&request_body);
request_builder.send().await.map_err(ApiError::from)
}
@@ -1122,8 +1098,7 @@ mod tests {
now_unix_timestamp, oauth_token_is_expired, resolve_saved_oauth_token,
resolve_startup_auth_source, AnthropicClient, AuthSource, OAuthTokenSet,
};
use crate::extra_headers::ExtraHeadersHook;
use crate::types::{ContentBlockDelta, InputMessage, MessageRequest};
use crate::types::{ContentBlockDelta, MessageRequest};
fn temp_config_home() -> std::path::PathBuf {
std::env::temp_dir().join(format!(
@@ -1916,58 +1891,4 @@ mod tests {
crate::error::ApiError::InvalidSseFrame(_)
));
}
#[tokio::test]
async fn extra_headers_provider_annotates_the_wire_request() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
let address = listener.local_addr().expect("local addr");
let (request_tx, request_rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept connection");
let mut buffer = [0_u8; 8192];
let read = stream.read(&mut buffer).expect("read request");
request_tx
.send(String::from_utf8_lossy(&buffer[..read]).into_owned())
.expect("send request");
let body = r#"{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}"#;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
body.len(),
body
);
stream
.write_all(response.as_bytes())
.expect("write response");
});
let client = AnthropicClient::new("test-key")
.with_base_url(format!("http://{address}"))
.with_extra_headers_provider(ExtraHeadersHook::new(
|ctx: &crate::extra_headers::ExtraHeadersContext<'_>| {
vec![(
"x-route".to_string(),
format!("{}/{}", ctx.provider, ctx.model),
)]
},
));
let request = MessageRequest {
model: "claude-sonnet-4".to_string(),
max_tokens: 16,
messages: vec![InputMessage::user_text("hello")],
..Default::default()
};
let response = client.send_raw_request(&request).await.expect("response");
assert_eq!(response.status(), reqwest::StatusCode::OK);
let captured = request_rx
.recv_timeout(Duration::from_secs(5))
.expect("captured request");
assert!(
captured
.to_lowercase()
.contains("x-route: anthropic/claude-sonnet-4"),
"wire request must carry the provider header: {captured}"
);
}
}
+9 -84
View File
@@ -8,7 +8,6 @@ use serde::Deserialize;
use serde_json::{json, Value};
use crate::error::ApiError;
use crate::extra_headers::{ExtraHeadersContext, ExtraHeadersHook};
use crate::http_client::build_http_client_or_default;
use crate::types::{
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
@@ -130,7 +129,6 @@ pub struct OpenAiCompatClient {
max_retries: u32,
initial_backoff: Duration,
max_backoff: Duration,
extra_headers: Option<ExtraHeadersHook>,
}
impl OpenAiCompatClient {
@@ -152,7 +150,6 @@ impl OpenAiCompatClient {
max_retries: DEFAULT_MAX_RETRIES,
initial_backoff: DEFAULT_INITIAL_BACKOFF,
max_backoff: DEFAULT_MAX_BACKOFF,
extra_headers: None,
}
}
@@ -188,7 +185,6 @@ impl OpenAiCompatClient {
max_retries: DEFAULT_MAX_RETRIES,
initial_backoff: DEFAULT_INITIAL_BACKOFF,
max_backoff: DEFAULT_MAX_BACKOFF,
extra_headers: None,
})
}
@@ -229,15 +225,6 @@ impl OpenAiCompatClient {
self
}
/// Install a provider that may add outbound headers to each model request.
///
/// The provider sees the final JSON body and can only add headers.
#[must_use]
pub fn with_extra_headers_provider(mut self, provider: ExtraHeadersHook) -> Self {
self.extra_headers = Some(provider);
self
}
pub async fn send_message(
&self,
request: &MessageRequest,
@@ -366,25 +353,18 @@ impl OpenAiCompatClient {
check_request_body_size_for_base_url(request, self.config(), &self.base_url)?;
let request_url = chat_completions_endpoint(&self.base_url);
let request_body =
build_chat_completion_request_for_base_url(request, self.config(), &self.base_url);
let mut request_builder = self
.http
self.http
.post(&request_url)
.header("content-type", "application/json")
.bearer_auth(&self.api_key)
.json(&request_body);
if let Some(extra_headers) = &self.extra_headers {
request_builder = extra_headers.apply(
request_builder,
&ExtraHeadersContext {
provider: self.config.provider_name,
model: &request.model,
body: &request_body,
},
);
}
request_builder.send().await.map_err(ApiError::from)
.json(&build_chat_completion_request_for_base_url(
request,
self.config(),
&self.base_url,
))
.send()
.await
.map_err(ApiError::from)
}
fn backoff_for_attempt(&self, attempt: u32) -> Result<Duration, ApiError> {
@@ -1886,7 +1866,6 @@ mod tests {
OpenAiCompatClient, OpenAiCompatConfig, StreamState,
};
use crate::error::ApiError;
use crate::extra_headers::ExtraHeadersHook;
use crate::test_env_lock as env_lock;
use crate::types::{
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
@@ -3163,58 +3142,4 @@ mod tests {
assert_eq!(super::strip_routing_prefix("kimi-k2.5"), "kimi-k2.5"); // no prefix, unchanged
assert_eq!(super::strip_routing_prefix("kimi/kimi-k1.5"), "kimi-k1.5");
}
#[tokio::test]
async fn extra_headers_provider_annotates_the_wire_request() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
let address = listener.local_addr().expect("local addr");
let (request_tx, request_rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept connection");
let mut buffer = [0_u8; 8192];
let read = stream.read(&mut buffer).expect("read request");
request_tx
.send(String::from_utf8_lossy(&buffer[..read]).into_owned())
.expect("send request");
let body = r#"{"id":"chatcmpl-test","object":"chat.completion","created":0,"model":"gpt-4o-mini","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}"#;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
body.len(),
body
);
stream
.write_all(response.as_bytes())
.expect("write response");
});
let client = OpenAiCompatClient::new("test-key", OpenAiCompatConfig::openai())
.with_base_url(format!("http://{address}"))
.with_extra_headers_provider(ExtraHeadersHook::new(
|ctx: &crate::extra_headers::ExtraHeadersContext<'_>| {
vec![(
"x-route".to_string(),
format!("{}/{}", ctx.provider, ctx.model),
)]
},
));
let request = MessageRequest {
model: "gpt-4o-mini".to_string(),
max_tokens: 16,
messages: vec![InputMessage::user_text("hello")],
..Default::default()
};
let response = client.send_raw_request(&request).await.expect("response");
assert_eq!(response.status(), reqwest::StatusCode::OK);
let captured = request_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("captured request");
assert!(
captured
.to_lowercase()
.contains("x-route: openai/gpt-4o-mini"),
"wire request must carry the provider header: {captured}"
);
}
}
+1 -1
View File
@@ -82,7 +82,7 @@ async fn send_message_posts_json_and_parses_response() {
);
assert_eq!(
request.headers.get("user-agent").map(String::as_str),
Some("claude-code/0.1.16")
Some("claude-code/0.1.14")
);
assert_eq!(
request.headers.get("anthropic-beta").map(String::as_str),
+26 -129
View File
@@ -480,9 +480,11 @@ impl ConfigLoader {
continue;
};
let ParsedConfigFile { mut object, source } = parsed;
let settings_warnings =
strip_untrusted_project_settings(entry.source, &mut object, &entry.path);
all_warnings.extend(settings_warnings);
if let Some(warning) =
strip_untrusted_project_hooks(entry.source, &mut object, &entry.path)
{
all_warnings.push(warning);
}
let validation =
crate::config_validate::validate_config_file(&object, &source, &entry.path);
if !validation.is_ok() {
@@ -525,9 +527,11 @@ impl ConfigLoader {
continue;
};
let ParsedConfigFile { mut object, source } = parsed;
let settings_warnings =
strip_untrusted_project_settings(entry.source, &mut object, &entry.path);
all_warnings.extend(settings_warnings);
if let Some(warning) =
strip_untrusted_project_hooks(entry.source, &mut object, &entry.path)
{
all_warnings.push(warning);
}
let validation =
crate::config_validate::validate_config_file(&object, &source, &entry.path);
if !validation.is_ok() {
@@ -603,9 +607,11 @@ impl ConfigLoader {
};
let ParsedConfigFile { mut object, source } = parsed;
let settings_warnings =
strip_untrusted_project_settings(entry.source, &mut object, &entry.path);
warnings.extend(settings_warnings);
if let Some(warning) =
strip_untrusted_project_hooks(entry.source, &mut object, &entry.path)
{
warnings.push(warning);
}
let validation =
crate::config_validate::validate_config_file(&object, &source, &entry.path);
if !validation.is_ok() {
@@ -675,55 +681,21 @@ impl ConfigLoader {
}
}
fn strip_untrusted_project_settings(
fn strip_untrusted_project_hooks(
source: ConfigSource,
object: &mut BTreeMap<String, JsonValue>,
path: &Path,
) -> Vec<String> {
// Project settings come from the repository and there is no project trust
// approval flow yet. User and local settings remain eligible.
// We strip hooks (all types) and permissions grants (allow, defaultMode),
// but keep permission restrictions (deny, ask) as they only limit access.
let mut warnings = Vec::new();
if source == ConfigSource::Project {
// Strip hooks entirely
if object.remove("hooks").is_some() {
warnings.push(format!(
"Ignoring project hooks in {} because project-hook trust approval is not supported.",
path.display()
));
}
// The legacy top-level `permissionMode` key selects the mode too.
if object.remove("permissionMode").is_some() {
warnings.push(format!(
"Ignoring project permissionMode in {} because project trust approval is not supported.",
path.display()
));
}
// Strip permissions.allow and permissions.defaultMode, keep deny and ask
if let Some(JsonValue::Object(permissions)) = object.get_mut("permissions") {
let had_allow = permissions.remove("allow").is_some();
let had_default_mode = permissions.remove("defaultMode").is_some();
if had_allow {
warnings.push(format!(
"Ignoring project permissions.allow in {} because project trust approval is not supported.",
path.display()
));
}
if had_default_mode {
warnings.push(format!(
"Ignoring project permissions.defaultMode in {} because project trust approval is not supported.",
path.display()
));
}
}
) -> Option<String> {
// Project settings come from the repository and there is no project-hook
// trust approval flow yet. User and local settings remain eligible.
if source == ConfigSource::Project && object.remove("hooks").is_some() {
Some(format!(
"Ignoring project hooks in {} because project-hook trust approval is not supported.",
path.display()
))
} else {
None
}
warnings
}
impl ConfigFileReport {
@@ -3733,81 +3705,6 @@ mod tests {
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn project_config_permissions_cannot_grant_access() {
// given
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
let project_settings = cwd.join(".claw").join("settings.json");
fs::create_dir_all(project_settings.parent().expect("project config dir"))
.expect("create project config dir");
fs::create_dir_all(&home).expect("home config dir");
// Project tries to grant permissions.allow and set defaultMode to danger-full-access,
// but also includes restrictive permissions that should be kept
fs::write(
&project_settings,
r#"{"permissions":{"allow":["bash"],"defaultMode":"dontAsk","deny":["rm"],"ask":["Edit"]}}"#,
)
.expect("write untrusted project permissions");
// when
let (loaded, warnings) = ConfigLoader::new(&cwd, &home)
.load_collecting_warnings()
.expect("config should load");
// then: project permissions.allow and defaultMode are stripped, but deny and ask remain
assert!(loaded.permission_rules().allow().is_empty());
assert_eq!(loaded.permission_mode(), None);
assert_eq!(loaded.permission_rules().deny(), &["rm".to_string()]);
assert_eq!(loaded.permission_rules().ask(), &["Edit".to_string()]);
assert_eq!(
warnings
.iter()
.filter(|warning| warning.contains("Ignoring project permissions.allow"))
.count(),
1
);
assert_eq!(
warnings
.iter()
.filter(|warning| warning.contains("Ignoring project permissions.defaultMode"))
.count(),
1
);
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn project_config_legacy_permission_mode_cannot_escalate() {
// given
let root = temp_dir();
let cwd = root.join("project");
let home = root.join("home").join(".claw");
fs::create_dir_all(&cwd).expect("project dir");
fs::create_dir_all(&home).expect("home config dir");
fs::write(
cwd.join(".claw.json"),
r#"{"permissionMode":"danger-full-access"}"#,
)
.expect("write untrusted legacy project permission mode");
// when
let (loaded, warnings) = ConfigLoader::new(&cwd, &home)
.load_collecting_warnings()
.expect("config should load");
// then
assert_eq!(loaded.permission_mode(), None);
assert!(warnings
.iter()
.any(|warning| warning.contains("Ignoring project permissionMode")));
fs::remove_dir_all(root).expect("cleanup temp dir");
}
#[test]
fn permission_mode_aliases_resolve_to_expected_modes() {
// given / when / then
+1 -28
View File
@@ -802,16 +802,7 @@ impl CommandWithStdin {
) -> std::io::Result<CommandExecution> {
let mut child = self.command.spawn()?;
if let Some(mut child_stdin) = child.stdin.take() {
// A hook that exits without reading all of its stdin closes the pipe
// while the payload is still being written, which fails with
// `BrokenPipe`. That is not a hook failure: its exit status and
// output are still collected below. Same handling as the plugin hook
// runner in `plugins/src/hooks.rs`.
match child_stdin.write_all(stdin) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(error) => return Err(error),
}
child_stdin.write_all(stdin)?;
}
loop {
@@ -869,24 +860,6 @@ mod tests {
assert_eq!(result, HookRunResult::allow(vec!["pre ok".to_string()]));
}
#[test]
#[cfg(unix)]
fn hook_that_ignores_stdin_is_not_failed_by_a_payload_larger_than_the_pipe() {
// The hook never reads stdin and exits while the runner is still writing
// a payload that does not fit in the pipe buffer, so the write fails with
// `BrokenPipe`. The hook itself succeeded and must not be reported as failed.
let runner = HookRunner::new(RuntimeHookConfig::new(
vec![crate::test_hook("pre ok", "", 0, 0)],
Vec::new(),
Vec::new(),
));
let tool_input = serde_json::json!({ "content": "x".repeat(70_000) }).to_string();
let result = runner.run_pre_tool_use("write_file", &tool_input);
assert_eq!(result, HookRunResult::allow(vec!["pre ok".to_string()]));
}
#[test]
fn object_style_hook_matchers_filter_runtime_execution() {
let runner = HookRunner::new(RuntimeHookConfig::from_hook_commands(
+2 -2
View File
@@ -1255,7 +1255,7 @@ mod tests {
fs::create_dir_all(root.join(".claw")).expect("claw dir");
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write instructions");
fs::write(
root.join(".claw").join("settings.local.json"),
root.join(".claw").join("settings.json"),
r#"{"permissionMode":"acceptEdits"}"#,
)
.expect("write settings");
@@ -1418,7 +1418,7 @@ mod tests {
fs::create_dir_all(root.join(".claw")).expect("claw dir");
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write CLAUDE.md");
fs::write(
root.join(".claw").join("settings.local.json"),
root.join(".claw").join("settings.json"),
r#"{"permissionMode":"acceptEdits"}"#,
)
.expect("write settings");