# PR #45753 完整报告

- 仓库：`vllm-project/vllm`
- 标题：[Rust Frontend] Add CORS support
- 合并时间：2026-06-16 21:47
- 原文链接：http://prhub.com.cn/vllm-project/vllm/pull/45753

---

## 执行摘要

本 PR 为 Rust 前端添加了完整的 CORS 支持，基于 `tower_http::cors::CorsLayer` 构建，精确匹配 Python 前端 Starlette `CORSMiddleware` 的行为。新增了 `--allowed-origins` 等 CLI 参数以及一个在无 Origin 请求时剥离 CORS 头部的中间件。默认配置允许任意源，确保与 Python 前端的向后兼容性。该 PR 包含充分的测试覆盖。

## 功能与动机

Rust 前端在浏览器环境中使用时，跨域请求会被浏览器阻止。本 PR 旨在填补这一功能空白，使 Rust 前端能够像 Python 前端一样正确处理 CORS。跟踪 Issue #44280。PR 将 Python 前端的默认行为（允许任意源）作为默认值，降低用户从 Python 迁移的适配成本。

## 实现拆解

1. **配置定义 **（`rust/src/server/src/config.rs`）：新增 `CorsConfig` 结构体，包含 `allow_origins`、`allow_methods`、`allow_headers`、`allow_credentials` 四个字段。实现了 `Default`（默认全通配）和 `validate` 方法（启动前校验非通配符值的合法性）。

2. **CLI 参数扩展 **（`rust/src/cmd/src/cli.rs`）：在 `SharedRuntimeArgs` 中增加四个 CORS 标志。由于 clap 对 `Vec<String>` 的内部解析限制，新增 `JsonStringList` 新类型以支持 JSON 数组格式（如 `'["*"]'`），并为其设置了自定义 `value_parser`。

3. **CORS 中间件 **（`rust/src/server/src/middleware/cors.rs`）：核心函数 `cors_layer` 根据 `CorsConfig` 构建 `CorsLayer`，处理通配符展开（`*` 展开为具体方法 / 头部列表）、`Vary` 头部动态发射、credentials 与通配符冲突时反射 Origin 等细节。`strip_cors_on_no_origin` 中间件在请求无 Origin 头部时删除所有 CORS 响应头，保持非浏览器请求的响应简洁。

4. **状态集成 **（`rust/src/server/src/state.rs`）：`AppState` 新增 `cors` 字段，提供 `with_cors` 链式方法。路由构建（`routes.rs`、`lib.rs`）中将 CORS 中间件插入中间件栈（位于认证之后，但 OPTIONS 预检绕过认证）。

5. **测试覆盖**：
 - CLI 测试（`cli/tests.rs`）：验证默认值、显式 JSON 列表解析、`--allow-credentials` 标志。
 - 集成测试（`routes/tests.rs`）：覆盖简单请求（判断 `Access-Control-Allow-Origin: *` 和无 `Vary`）、预检请求（返回显式方法和 max-age）、无 Origin 请求（无 CORS 头部）、显式源列表（允许 / 拒绝）、credentials + 通配符（反射 Origin 并带 `Vary`）等场景。

### `rust/src/server/src/config.rs`

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

```rust
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`

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

```rust
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);
}

```

## 评论区精华

> **自动化工具建议**：增加 `--no-allow-credentials` 以匹配 Python 的 `BooleanOptionalAction`。
> **作者回复**：Rust 前端使用 `--flag false` 而非 `--no-` 形式，其他已实现布尔标志均遵循此模式。

> **BugenZhao 提问**：`cors_layer` 能否做到无 Origin 请求时完全跳过？
> **作者回复**：`tower_http::cors::CorsLayer` 无法按请求动态跳过，当前方案通过 `strip_cors_on_no_origin` 中间件在无 Origin 时删除 CORS 头部，效果相同且避免引入自定义 `Service`。

> **BugenZhao 提问**：`allowed_origins` 等字段能否直接用 `Vec<String>` 而不用 `JsonStringList`？
> **作者回复**：clap 将 `Vec<String>` 视为重复参数并逐元素解析，无法挂载整体 JSON 解析器。BugenZhao 查阅文档后确认新类型是正确方案。

## 风险与影响

- **安全风险**：默认允许任意源，若生产环境未限制 origin，可能被恶意网站通过 XHR 访问 API。但该默认值与 Python 前端一致，团队需在文档中强调配置限制。
- **行为差异**：拒绝预检返回 200（而非 400），裸 OPTIONS 返回 200（而非 405）。浏览器行为相同，但可能影响依赖状态码的网关或客户端。
- **性能影响**：`strip_cors_on_no_origin` 在无 Origin 请求上仍经过中间件栈，但影响可忽略。
- **配置迁移**：`--allow-credentials` 的 `--no-` 形式不支持，用户需调整为 `--allow-credentials false`。

影响范围：Rust 前端用户可以直接通过浏览器使用 API；团队需要维护与 Python 前端的 CORS 行为一致性。

## 关联脉络

本 PR 是 Issue #44280 的实现，属于 Rust 前端功能补全系列的一部分。在此之前，Rust 前端已支持请求 ID 头（#45696）、日志等，CORS 支持是向 Python 前端功能对齐的关键一步。后续可能继续补充 `--ssl-keyfile` 等尚未移植的 CLI 参数。