Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/openshell-bootstrap/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,9 @@ fn glob_match(pattern: &str, path: &str, is_dir: bool) -> bool {
return true;
}
for (idx, _) in path.match_indices('/') {
if glob_match(rest, &path[idx + 1..], is_dir) {
if let Some(suffix) = path.get(idx + 1..)
&& glob_match(rest, suffix, is_dir)
{
return true;
}
}
Expand Down Expand Up @@ -592,6 +594,7 @@ mod tests {
assert!(glob_match("**/*.log", "a/b/c.log", false));
assert!(glob_match("**/*.log", "c.log", false));
assert!(!glob_match("**/*.log", "c.txt", false));
assert!(glob_match("**/föö.log", "a/b/föö.log", false));
}

#[test]
Expand Down
8 changes: 7 additions & 1 deletion crates/openshell-bootstrap/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ pub fn extract_host_from_ssh_destination(destination: &str) -> String {

// Handle user@host format
dest.find('@')
.map_or_else(|| dest.to_string(), |at_pos| dest[at_pos + 1..].to_string())
.and_then(|at_pos| dest.get(at_pos + 1..))
.map_or_else(|| dest.to_string(), ToString::to_string)
}

/// Resolve an SSH host alias to the actual hostname or IP address.
Expand Down Expand Up @@ -457,6 +458,11 @@ mod tests {
);
}

#[test]
fn extract_host_user_at_multi_byte_hostname() {
assert_eq!(extract_host_from_ssh_destination("user@mülti"), "mülti");
}

#[test]
fn metadata_roundtrip() {
let meta = GatewayMetadata {
Expand Down
23 changes: 22 additions & 1 deletion crates/openshell-core/src/provider_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ impl ProviderCredentialState {
DEFAULT_EXPIRES_IN
} else {
let now = crate::time::now_ms();
(expires_at_ms - now) / 1000
expires_at_ms.saturating_sub(now) / 1000
}
},
);
Expand Down Expand Up @@ -587,6 +587,27 @@ mod tests {
);
}

#[test]
fn gcp_token_response_handles_already_expired_token_without_panic() {
let now_ms = i64::try_from(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis(),
)
.unwrap();
let state = ProviderCredentialState::from_environment(
1,
HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), "adc-tok".to_string())]),
HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), now_ms - 1_000)]),
HashMap::new(),
);
assert!(
state.gcp_token_response().is_none(),
"expired token should be skipped rather than panic"
);
}

#[test]
fn child_env_with_gcp_resolved_resolves_vertex_vars_without_metadata_host() {
let state = ProviderCredentialState::from_environment(
Expand Down
23 changes: 22 additions & 1 deletion crates/openshell-policy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1440,7 +1440,13 @@ fn truncate_for_display(s: &str) -> String {
if s.len() <= 80 {
s.to_string()
} else {
format!("{}...", &s[..77])
// Back off to a char boundary: slicing at a fixed byte index panics
// on multi-byte UTF-8 (e.g. non-ASCII characters in policy paths).
let mut end = 77;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &s[..end])
}
}

Expand All @@ -1462,6 +1468,21 @@ pub use openshell_core::paths::normalize_path;
mod tests {
use super::*;

#[test]
fn truncate_for_display_handles_multi_byte_utf8_without_panicking() {
// Byte index 77 falls inside the multi-byte 'é'.
let s = format!("/{}{}", "a".repeat(75), "é".repeat(100));
let truncated = truncate_for_display(&s);
assert!(truncated.ends_with("..."));
assert!(truncated.len() <= 80);
}

#[test]
fn truncate_for_display_leaves_short_strings_untouched() {
let s = "short path";
assert_eq!(truncate_for_display(s), s);
}

/// Verify that the serialized YAML uses `filesystem_policy` (not
/// `filesystem`) so it can be fed back to `parse_sandbox_policy`.
#[test]
Expand Down
149 changes: 143 additions & 6 deletions crates/openshell-router/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ const VERTEX_ANTHROPIC_VERSION: &str = "vertex-2023-10-16";
const COMMON_INFERENCE_REQUEST_HEADERS: [&str; 4] =
["content-type", "accept", "accept-encoding", "user-agent"];

/// Anthropic-SDK-only body fields that Vertex AI rawPredict does not accept.
/// Vertex AI's rawPredict endpoint uses strict pydantic validation and rejects
/// any extra inputs not in its schema. The Anthropic SDKs' native Vertex
/// transport (`AnthropicVertex`) strips these automatically; we must do the same
/// when proxying through `inference.local`.
///
/// `model` is handled separately (rewritten or stripped depending on route type)
/// and is intentionally omitted here.
const VERTEX_UNSUPPORTED_BODY_FIELDS: &[&str] = &["context_management"];

impl StreamingProxyResponse {
/// Create from a fully-buffered [`ProxyResponse`] (for mock routes).
pub fn from_buffered(resp: ProxyResponse) -> Self {
Expand Down Expand Up @@ -281,11 +291,12 @@ fn prepare_backend_request(
let needs_vertex_anthropic_version = is_vertex_anthropic_rawpredict_route(route);
if needs_vertex_anthropic_version {
// Vertex AI rawPredict encodes the model in the URL path, not
// the request body. Clients using the standard Anthropic API
// (e.g. Claude Code via inference.local) always send "model"
// in the body; strip it so Vertex AI does not reject the
// request with "Extra inputs are not permitted".
// the request body. Strip "model" and any Anthropic-SDK-only
// beta fields that Vertex's strict pydantic validation rejects.
obj.remove("model");
for field in VERTEX_UNSUPPORTED_BODY_FIELDS {
obj.remove(*field);
}
} else if route_is_bedrock(route) {
// AWS Bedrock InvokeModel encodes the model in the URL
// path; the request body is the raw provider-specific
Expand Down Expand Up @@ -824,8 +835,12 @@ fn build_backend_url(endpoint: &str, path: &str) -> String {
let base_path = &base[path_start..];
base_path.starts_with("/v1/") || base_path.ends_with("/v1")
});
if base_path_has_v1_edge_segment && (path == "/v1" || path.starts_with("/v1/")) {
return format!("{base}{}", &path[3..]);
if base_path_has_v1_edge_segment
&& let Some(rest) = path
.strip_prefix("/v1")
.filter(|rest| rest.is_empty() || rest.starts_with('/'))
{
return format!("{base}{rest}");
}

format!("{base}{path}")
Expand Down Expand Up @@ -1970,6 +1985,128 @@ mod tests {
);
}

#[tokio::test]
async fn vertex_ai_body_strips_unsupported_beta_fields() {
let mock_server = MockServer::start().await;

let base_path = "/v1/projects/my-project/locations/us-east5/publishers/anthropic/models";
let route = ResolvedRoute {
name: "vertex-anthropic".to_string(),
endpoint: format!("{}{base_path}", mock_server.uri()),
model: "claude-sonnet-4-6@20250514".to_string(),
api_key: "ya29.token".to_string(),
protocols: vec!["anthropic_messages".to_string()],
auth: AuthHeader::Bearer,
default_headers: Vec::new(),
passthrough_headers: Vec::new(),
timeout: DEFAULT_ROUTE_TIMEOUT,
model_in_path: true,
request_path_override: Some(":rawPredict".to_string()),
};

Mock::given(method("POST"))
.and(path(format!(
"{base_path}/claude-sonnet-4-6@20250514:rawPredict"
)))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "msg_1"})),
)
.mount(&mock_server)
.await;

let client = reqwest::Client::builder().build().unwrap();
let body = bytes::Bytes::from(
serde_json::to_vec(&serde_json::json!({
"model": "claude-sonnet-4-6-20250514",
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 32,
"context_management": {"enabled": true},
}))
.unwrap(),
);
let headers = vec![("content-type".to_string(), "application/json".to_string())];

let (builder, _url) = prepare_backend_request(
&client,
&route,
"POST",
"/v1/messages",
&headers,
body,
false,
)
.unwrap();

let response = builder.send().await.unwrap();
assert_eq!(response.status().as_u16(), 200);
let received = mock_server.received_requests().await.unwrap();
let received_body: serde_json::Value = serde_json::from_slice(&received[0].body).unwrap();
let obj = received_body.as_object().unwrap();
assert!(
!obj.contains_key("context_management"),
"context_management must be stripped for Vertex AI rawPredict, got: {received_body}"
);
assert!(
!obj.contains_key("model"),
"model must also be stripped for Vertex AI rawPredict, got: {received_body}"
);
assert!(
obj.contains_key("messages"),
"standard fields must be preserved, got: {received_body}"
);
}

#[tokio::test]
async fn direct_anthropic_preserves_beta_fields() {
let route = ResolvedRoute {
name: "direct-anthropic".to_string(),
endpoint: "https://api.anthropic.com/v1".to_string(),
model: "claude-sonnet-4-6-20250514".to_string(),
api_key: "sk-test".to_string(),
protocols: vec!["anthropic_messages".to_string()],
auth: AuthHeader::Custom("x-api-key"),
default_headers: Vec::new(),
passthrough_headers: Vec::new(),
timeout: DEFAULT_ROUTE_TIMEOUT,
model_in_path: false,
request_path_override: None,
};

let client = reqwest::Client::builder().build().unwrap();
let body = bytes::Bytes::from(
serde_json::to_vec(&serde_json::json!({
"model": "claude-sonnet-4-6-20250514",
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 32,
"context_management": {"enabled": true},
}))
.unwrap(),
);
let headers = vec![("content-type".to_string(), "application/json".to_string())];

let (builder, _url) = prepare_backend_request(
&client,
&route,
"POST",
"/v1/messages",
&headers,
body,
false,
)
.unwrap();

let request = builder.build().unwrap();
let sent_body: serde_json::Value =
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
assert!(
sent_body
.as_object()
.unwrap()
.contains_key("context_management"),
"context_management must be preserved for direct Anthropic API routes"
);
}

#[tokio::test]
async fn vertex_ai_body_preserves_client_anthropic_version() {
// When the client already sends anthropic_version, the router must NOT overwrite it.
Expand Down
Loading
Loading