Prhub

#45753 [Rust Frontend] Add CORS support

原始 PR 作者 tahsintunan 合并时间 2026-06-16 21:47 文件变更 12 提交数 3 评论 10 代码增减 +732 / -42

执行摘要

Rust 前端新增 CORS 支持,匹配 Python 行为

Rust 前端需要 CORS 支持以处理浏览器跨域请求,跟踪 Issue #44280。目前 Python 前端通过 Starlette 的 CORSMiddleware 提供此功能,Rust 前端需要等效实现以保证用户迁移时行为一致。

建议精读 rust/src/server/src/middleware/cors.rs 中的 cors_layer 和 strip_cors_on_no_origin 实现,理解通配符与 credentials 冲突的处理策略,以及如何通过 Vary 头部优化缓存。CLI 侧 JsonStringList 的类型包装也是一个值得注意的模式。

讨论亮点
  • CLI 参数命名风格:自动化工具建议增加 --no-allow-credentials 以匹配 Python 的 BooleanOptionalAction。作者回复 Rust 前端使用 --flag false 而非 --no- 形式,且其他已实现布尔标志均遵循此模式,因此保持现有设计。
  • CLI 类型选择:BugenZhao 询问是否可直接使用 Vec<String> 代替 JsonStringList 新类型。作者解释 clap 对 Vec 的内部解析限制导致无法附加自定义 value_parser,BugenZhao 查询文档后确认新类型为合理方案。
  • 中间件跳过权衡:BugenZhao 建议在无 Origin 请求时完全绕过 CorsLayer 以提升性能。作者指出 tower_http::cors::CorsLayer 无法按请求动态跳过,当前使用 strip_cors_on_no_origin 中间件在无 Origin 时删除 CORS 头部,虽非完全绕过但效果相同,且避免引入自定义 Service 的复杂性。

实现拆解

  1. 新增 CorsConfig 配置结构体(rust/src/server/src/config.rs):定义 allow_origins、allow_methods、allow_headers 和 allow_credentials 字段,提供默认值(通配符 ["*"])和启动前校验逻辑。
  2. 扩展 CLI 参数(rust/src/cmd/src/cli.rs):新增 --allowed-origins、--allowed-methods、--allowed-headers、--allow-credentials 标志,通过 JsonStringList 新类型解析 JSON 数组格式的值,保持与 Python CLI 的兼容性。
  3. 实现 CORS 中间件(rust/src/server/src/middleware/cors.rs):核心函数 cors_layer 根据 CorsConfig 构建 tower_http::cors::CorsLayer,处理通配符展开、Vary 头部条件发射、credentials 与通配符冲突等细节;strip_cors_on_no_origin 中间件在请求无 Origin 头部时剥离 CORS 响应头,保持非跨域请求的响应简洁。
  4. 集成到应用状态(rust/src/server/src/state.rs):AppState 新增 cors 字段,提供 with_cors 链式设置方法,并在路由构建(rust/src/server/src/lib.rs、rust/src/server/src/routes.rs)中注入中间件。
  5. 测试覆盖:新增单元测试(rust/src/cmd/src/cli/tests.rs)验证 CLI 默认值和解析;新增集成测试(rust/src/server/src/routes/tests.rs)覆盖简单请求、预检请求、无 Origin 请求、显式源等场景。
文件 模块 状态 重要度
rust/src/server/src/middleware/cors.rs 中间件 added 8.47
rust/src/server/src/config.rs 配置 modified 7.4
rust/src/server/src/routes/tests.rs 测试 modified 8.69
rust/src/cmd/src/cli.rs CLI modified 6.91
rust/src/server/src/state.rs 状态管理 modified 5.94

关键符号

cors_layer strip_cors_on_no_origin CorsConfig::validate CorsConfig::default AppState::with_cors

关键源码片段

rust/src/server/src/config.rs data-contract

定义了 CorsConfig 结构体及其默认值和校验逻辑,是 CORS 配置的数据契约。

use axum::http::{HeaderName, HeaderValue, Method};
use anyhow::{Result, bail};
use serde::Serialize;
​
/// CORS settings mirroring Python's `CORSMiddleware`; the default is permissive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CorsConfig {
    /// Allowed origins. `["*"]` allows any origin.
    pub allow_origins: Vec<String>,
    /// Allowed methods. `["*"]` allows the standard method set.
    pub allow_methods: Vec<String>,
    /// Allowed request headers. `["*"]` mirrors the requested headers.
    pub allow_headers: Vec<String>,
    /// Whether to allow credentials (cookies, authorization headers).
    pub allow_credentials: bool,
}
​
impl Default for CorsConfig {
    fn default() -> Self {
        Self {
            allow_origins: vec!["*".to_string()],
            allow_methods: vec!["*".to_string()],
            allow_headers: vec!["*".to_string()],
            allow_credentials: false,
        }
    }
}
​
impl CorsConfig {
    /// Validate that non-wildcard values parse into HTTP types, so the CORS
    /// layer can be built infallibly after startup validation has run.
    pub fn validate(&self) -> Result<()> {
        for origin in &self.allow_origins {
            if origin != "*" {
                origin.parse::<HeaderValue>().map_err(|e| {
                    anyhow::anyhow!("invalid --allowed-origins value {origin:?}: {e}")
                })?;
            }
        }
        for method in &self.allow_methods {
            if method != "*" {
                method.parse::<Method>().map_err(|e| {
                    anyhow::anyhow!("invalid --allowed-methods value {method:?}: {e}")
                })?;
            }
        }
        for header in &self.allow_headers {
            if header != "*" {
                header.parse::<HeaderName>().map_err(|e| {
                    anyhow::anyhow!("invalid --allowed-headers value {header:?}: {e}")
                })?;
            }
        }
        Ok(())
    }
}
rust/src/server/src/routes/tests.rs test-coverage

集成测试,覆盖了 CORS 默认行为、预检请求、无 Origin 请求等关键场景,保证实现正确性。

use crate::config::{ApiServerOptions, CorsConfig};
use crate::state::AppState;
​
/// Helper: build an app with a given CORS config and optional API keys.
async fn test_app_with_cors_and_keys(
    cors: CorsConfig,
    api_keys: Vec<String>,
) -> (axum::Router, MockEngineTask) {
    let (chat, engine_task) = test_models_with_engine_outputs_and_backend(
        b"engine-openai-cors",
        default_stream_output_specs(),
        Arc::new(FakeChatBackend::new()),
    )
    .await;
    let app = build_router(Arc::new(
        AppState::new(vec!["Qwen/Qwen1.5-0.5B-Chat".to_string()], chat)
            .with_cors(cors)
            .with_api_keys(api_keys),
    ));
    (app, engine_task)
}
​
/// Helper: build an app with CORS only.
async fn test_app_with_cors(cors: CorsConfig) -> (axum::Router, MockEngineTask) {
    test_app_with_cors_and_keys(cors, vec![]).await
}
​
/// Extract a header value from the response as a string.
fn header_value<'a>(response: &'a axum::response::Response, name: &str) -> Option<&'a str> {
    response
        .headers()
        .get(name)
        .map(|value| value.to_str().expect("header is valid utf-8"))
}
​
/// Default CORS: simple GET with any Origin gets `Access-Control-Allow-Origin: *`,
/// and no `Vary` header (since wildcard without credentials).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn cors_default_simple_request_allows_any_origin() {
    let (mut app, _engine_task) = test_app_with_cors(CorsConfig::default()).await;
    let response = app
        .call(
            Request::builder()
                .method("GET")
                .uri("/v1/models")
                .header("origin", "http://example.com")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("call app");
​
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        header_value(&response, "access-control-allow-origin"),
        Some("*")
    );
    // Wildcard origins without credentials emit no `Vary` (Starlette parity).
    assert_eq!(header_value(&response, "vary"), None);
}

评论区精华

CLI 参数 --no-allow-credentials 缺失 设计

Codex 建议添加 --no-allow-credentials 标志以匹配 Python 的 BooleanOptionalAction。作者回复 Rust 前端风格是使用 --flag false,而不是 --no-flag,且其他已实现的布尔标志也遵循此模式。

结论:决定不添加 --no- 变体,维持现有 Rust 前端布尔标志的处理方式。 · 已解决

CORS 列表参数的 CLI 类型选择 设计

BugenZhao 询问能否直接使用 Vec<String> 替代 JsonStringList 新类型。作者解释 clap 对 Vec<String> 内部解析的限制,导致无法附加自定义 value_parser。BugenZhao 查询 clap 文档后确认新类型是合适的方案。

结论:保留 JsonStringList 新类型以正确解析 JSON 数组格式的参数。 · 已解决

是否可以在无 Origin 请求时完全绕过 CorsLayer 性能

BugenZhao 建议理想情况下在没有 Origin 头部时完全跳过 CorsLayer,避免不必要的 CORS 头部。作者指出 tower-http 的 CorsLayer 在构建时选择行为,无法按请求动态跳过,目前通过 strip_cors_on_no_origin 中间件在无 Origin 时删除 CORS 头部。讨论当前方案的可接受性。

结论:当前实现使用 strip_cors_on_no_origin 中间件来清理无 Origin 请求的 CORS 头部,虽然并非完全绕过,但达到了相同效果。 · 已解决

风险与影响

  1. 安全风险(rust/src/server/src/middleware/cors.rs):默认配置允许任意源(allow_origins: ["*"]),若用户未主动限制,可能被任意网站通过 AJAX 请求访问 API。但该行为与 Python 前端一致,属于已知权衡。
  2. 行为差异(rust/src/server/src/middleware/cors.rs):拒绝预检请求返回 200(空体)而非 Python 的 400,裸 OPTIONS 返回 200 而非 405。虽然浏览器行为相同,但直接调用 HTTP 接口的程序可能依赖状态码。
  3. 中间件性能:strip_cors_on_no_origin 在每个无 Origin 请求上仍经过中间件栈,增加少量开销,但对非浏览器场景可忽略。
  4. 配置同步:若用户从 Python 前端迁移 CLI 参数,--allow-credentials 的 --no- 形式不被支持,需调整为 --allow-credentials false。

用户影响:Rust 前端现在可以正确处理浏览器跨域请求,默认允许任意源,降低了使用门槛。系统影响:CORS 中间件默认启用,但用户可通过 CLI 配置限制源。团队影响:需保持与 Python 前端 CORS 行为的一致性,未来新增功能时需考虑两侧同步。

默认开启宽松 CORS 响应行为与 Python 略有差异 中间件性能影响 配置同步差异

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论