Skip to content
Open
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
3 changes: 2 additions & 1 deletion .github/workflows/gateway.yml
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,13 @@ jobs:
uses: ./.github/actions/setup-python-env
with:
python-version: "3.12"
- name: Check Gateway authentication and HTTP lifecycle over real listeners
- name: Check Gateway targets, authentication and HTTP lifecycle over real listeners
run: |
cargo build --locked --manifest-path gateway/Cargo.toml --bin pc-gateway
test -x gateway/target/debug/pc-gateway
export PC_GATEWAY_BINARY="$PWD/gateway/target/debug/pc-gateway"
uv run --locked --no-sync pytest \
tests/e2e/test_gateway_target_real_process.py \
tests/e2e/test_gateway_authentication.py \
tests/e2e/test_gateway_process_fixture.py \
tests/e2e/test_gateway_http1_lifecycle.py -q
24 changes: 24 additions & 0 deletions docs/en/docs/operate/install-gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,30 @@ For an upgrade, stop the Gateway, download and verify the matching release, repl
the existing configuration. Follow the Server's database maintenance requirements separately. Keep the previous binary
for operational rollback; replacing a Gateway binary does not roll back Core's database.


## Optional Core target binding

The default `PC_GATEWAY_TARGET_BINDING=compatible` preserves configured upstream URLs and the existing two-phase checks. Omitting the setting has the same behavior. Upgrading Core alone does not change destinations or require a new service role. The startup warning states that actual sends are not bound to Core's configured target. This warning is an operational log, not a per-call evidence marker.

The selected mode determines the deployment's destination source:

| Mode | Destination source | Core unavailable after startup |
| --- | --- | --- |
| Unset or `compatible` | Configured Gateway URL; Core checks do not establish that it matches the Core profile | Pause by default; marked memory-free fallback only with explicit `passthrough` and a startup-confirmed non-enforcing Core |
| `required` | Endpoint and matching protocol from each Core send admission, including every retry; no Gateway URL fallback | Pause; no degraded send |

Compatibility warnings do not establish destination equality. Required mode binds each admitted send to its Core-resolved endpoint; this does not prove exclusive delivery through proxies or provider account/region identity. See [the target-binding requirements](https://github.com/oceanbase/powercontext/issues/2460) for the broader contract.

Set `PC_GATEWAY_TARGET_BINDING=required` to use Core as the destination source. Core must advertise `powercontext.context-target.v1`, have target profiles in its inference protection configuration, and run enforced access control. `PC_GATEWAY_CORE_TOKEN` must authenticate an enforced service principal with `server.observe` (`server.observer`) on the Server and `gateway.invoke` (`gateway.user`) on every requested Scope. Capture additionally needs `scope.contribute`, for example through `scope.contributor`. Configure matching endpoint, model and protocol values in each Core profile. Chat uses `PC_GATEWAY_UPSTREAM_PROFILE` (default `default`); Responses uses `PC_GATEWAY_UPSTREAM_PROFILE_RESPONSES` and otherwise the Chat profile name. Use separate profiles when serving different protocols.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Document the required scope.read permission

A dedicated service identity with only the documented server.observer and gateway.user roles passed startup discovery against real Core, then the model request returned HTTP 503 after Core denied the check with HTTP 403. Adding scope.viewer on the same Scope restored HTTP 200. Please list scope.read, for example via scope.viewer, in both locales. Chinese counterpart


Required mode rejects startup if capability or identity cannot be confirmed, including timeouts, rejected probes and malformed replies. Each initial and retry admission must return a valid endpoint and matching renderer protocol; missing target information never falls back to a Gateway URL. Ordinary `PC_GATEWAY_UPSTREAM_URL*` settings are ignored in this mode. Subscription credentials retain their fixed destination constraints. Claude CLI remains available only in compatible mode with a confirmed non-enforcing Core; its unobservable internal sends cannot satisfy required binding.

`PC_GATEWAY_DEGRADE=passthrough` keeps its existing memory-free fallback only in compatible mode when startup discovery confirms a non-enforcing Core. It does not bypass explicit Core denials or malformed verdicts. A startup warning states whether this fallback is permitted or inactive based on the discovered Core protection state. Required mode treats it as pause and logs a warning. Unknown or empty target-binding settings are configuration errors.

Model HTTP requests continue to inherit environment proxies, including bypass rules. `PC_GATEWAY_UPSTREAM_PROXY=direct` disables inheritance; an explicit proxy URL selects a trusted proxy instead. Startup warns when proxy configuration is present without logging its value; configuration presence does not prove that a request used a proxy. Target binding does not authorize a proxy or prove exclusive delivery to the endpoint. An HTTP proxy can receive model bodies and provider credentials; an HTTPS CONNECT proxy normally observes destination metadata, and an intercepting proxy can observe decrypted traffic. Core HTTP RPCs remain direct.

A loopback listener without `PC_GATEWAY_API_KEY` retains its existing behavior and warns that local processes may invoke model routes. An explicitly empty or invalid key is rejected before listening. Non-loopback listeners still require a valid key. Required mode requires separate Core and Gateway credentials; compatible mode retains shared credentials with a startup warning. Health checks establish listener availability, not model readiness or target binding.

## Build from source

Check out the matching release tag and run `cargo build --locked --manifest-path gateway/Cargo.toml --release -p pc-gateway-app`.
Expand Down
24 changes: 24 additions & 0 deletions docs/zh/docs/operate/install-gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,27 @@ Server 的数据库维护要求需要单独遵循。保留旧二进制以便回
可执行文件位于 `gateway/target/release/pc-gateway`。未设置分发元数据的源码构建显示 Cargo 包版本及未知提交;
正式发布构建会嵌入发布身份。开发和测试说明见
[Gateway README](https://github.com/oceanbase/powercontext/blob/master/gateway/README.md)。


## 可选的 Core 目标绑定

默认的 `PC_GATEWAY_TARGET_BINDING=compatible` 保留已配置的上游 URL 和现有两阶段检查。不设置该项时行为相同。仅升级 Core 不会改变目标,也不会要求新增服务角色。启动告警会说明实际发送尚未与 Core 配置的目标绑定。该告警属于运行日志,不是逐次调用的 evidence 标记。

发送目标来源由部署模式决定:

| 模式 | 发送目标来源 | 启动后 Core 不可用 |
| --- | --- | --- |
| 未设置或 `compatible` | Gateway 配置的 URL;Core 检查不证明它与 Core profile 一致 | 默认暂停;仅显式配置 `passthrough` 且启动时确认 Core 不强制保护,才允许带标记的无记忆降级 |
| `required` | 每次 Core 发送准入返回的 endpoint 和匹配协议,包括每次重试;不回退到 Gateway URL | 暂停,不进行降级发送 |

兼容告警不证明目标一致。required 模式将每次获准发送绑定到 Core 解析的 endpoint;这不证明经代理时仅该目标收到数据,也不证明服务商账号或区域身份。完整契约见[目标绑定要求](https://github.com/oceanbase/powercontext/issues/2460)。

设置 `PC_GATEWAY_TARGET_BINDING=required` 后,Core 成为发送目标来源。Core 必须声明 `powercontext.context-target.v1`,在推理保护配置中具备目标 profile,并启用强制访问控制。`PC_GATEWAY_CORE_TOKEN` 必须认证强制模式下的 service principal,且在 Server 上拥有 `server.observe`(`server.observer`)、在每个请求 Scope 上拥有 `gateway.invoke`(`gateway.user`)。捕获还需要 `scope.contribute`,例如通过 `scope.contributor` 获得。在每个 Core profile 中配置匹配的 endpoint、model 和 protocol。Chat 使用 `PC_GATEWAY_UPSTREAM_PROFILE`(默认 `default`);Responses 使用 `PC_GATEWAY_UPSTREAM_PROFILE_RESPONSES`,未设置时复用 Chat profile 名称。服务不同协议时应使用独立 profile。

required 模式无法确认能力或身份时拒绝启动,包括超时、探测被拒绝和响应格式错误。首次发送与重试的每次准入都必须返回有效 endpoint 和匹配的渲染协议;缺少目标信息时绝不回退到 Gateway URL。该模式忽略普通 `PC_GATEWAY_UPSTREAM_URL*` 配置。订阅凭据仍受固定目标约束。Claude CLI 仅在 compatible 模式且已确认 Core 不强制保护时可用;其不可观察的内部发送无法满足 required 绑定。

`PC_GATEWAY_DEGRADE=passthrough` 仅在 compatible 模式、且启动发现确认 Core 不强制保护时保留现有无记忆降级。它不会绕过 Core 的明确拒绝或格式错误的裁决。启动告警会根据探测到的 Core 保护状态,明确说明本次是否允许该降级或该配置未生效。required 模式将其按 pause 处理并告警。未知或空的目标绑定配置属于配置错误。

模型 HTTP 请求继续继承环境代理,包括绕过规则。`PC_GATEWAY_UPSTREAM_PROXY=direct` 禁止继承;显式代理 URL 则选择一个受信代理。存在代理配置时启动会告警,但不记录配置值;存在配置不证明某次请求实际经过代理。目标绑定不批准代理,也不证明仅 endpoint 收到数据。HTTP 代理可以接收模型正文和服务商凭据;HTTPS CONNECT 代理通常观察目标元数据,拦截式代理则可观察解密流量。Core HTTP RPC 继续直连。

loopback 监听未配置 `PC_GATEWAY_API_KEY` 时保留现有行为,并告警本机进程可调用模型路由。显式空密钥或非法密钥会在监听前被拒绝。非 loopback 监听仍需要有效密钥。required 模式要求 Core 和 Gateway 凭据不同;compatible 模式保留共用凭据的行为并在启动时告警。健康检查只证明监听可用,不证明模型就绪或目标绑定生效。
1 change: 1 addition & 0 deletions e2e/bub/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions evaluation/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions gateway/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ getrandom = "0.4.3"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
url = "2"
hyper = { version = "1", features = ["client", "http1"] }
tower = { version = "0.5", features = ["util"] }
hyper-util = { version = "0.1", features = ["client", "client-legacy", "tokio", "http1"] }
Expand Down
6 changes: 6 additions & 0 deletions gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ The Rust process owns the public listener and forwards other routes to Core over

Request size, response buffering and concurrency have separate limits. The effective input limit includes Core's advertised capacity and the parser ceiling; increasing a deployment setting cannot bypass either. See [byte capacity](../docs/en/docs/operate/deploy-server.md#gateway-byte-capacity) for limits and failure statuses. Operational JSONL omits request and response bodies; its configuration is in [Gateway evidence](../docs/en/docs/operate/gateway-evidence.md).

## Target binding and compatibility

Default `PC_GATEWAY_TARGET_BINDING=compatible` preserves existing URL/profile configuration and permitted memory-free degradation, with a startup warning that sends are not Core-bound. Core upgrades never automatically migrate the mode. Opt in with `PC_GATEWAY_TARGET_BINDING=required`: startup requires target capability and an enforced service identity; every send and retry needs Core's endpoint and matching protocol, with no local URL fallback or degraded sends. Configure separate Chat/Responses profiles when their protocols differ. Claude CLI supports only compatible, non-enforcing deployments.

Model HTTP traffic retains environment proxy support; `PC_GATEWAY_UPSTREAM_PROXY=direct` disables it, or a proxy URL names a trusted hop. Proxy configuration and unauthenticated loopback model access produce fixed startup warnings without exposing configuration values. Explicitly empty API keys and invalid binding/proxy settings fail before listening. These are operational warnings, not per-call binding evidence. See [optional target binding](../docs/en/docs/operate/install-gateway.md#optional-core-target-binding) for role requirements, migration and proxy trust limits.

## OAuth subscriptions

`PC_GATEWAY_SUBSCRIPTION` selects `codex`, `copilot`, `grok`, `qwen`, `kimi`, `gemini` or `claude`. HTTP channels require an explicit credential path in `PC_GATEWAY_SUBSCRIPTION_CREDENTIALS`. Copilot, Qwen and Kimi also support `pc-gateway login <provider> <new-file>`.
Expand Down
4 changes: 4 additions & 0 deletions gateway/SUBSCRIPTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,7 @@ cargo test --locked --workspace -- --skip live_
```

The [shared OAuth fixtures](../tests/fixtures/oauth/README.md) and [upstream vector notes](../tests/fixtures/oauth/upstream/README.md) describe credential, protocol and process coverage. Tests use synthetic credentials and local peers; live entitlement, quota and installed CLI compatibility require separate verification. Copyright and license terms are in [LICENSES/oauth.md](../LICENSES/oauth.md).

## Target binding mode

Existing subscriptions keep their configured destinations in the default compatible mode. With `PC_GATEWAY_TARGET_BINDING=required`, each Core-approved endpoint must match the subscription's credential destination and protocol; a mismatch sends nothing. Claude CLI cannot satisfy this mode and is rejected before listening. It remains supported in compatible mode only when Core is confirmed non-enforcing. Environment proxy behavior and its trust limits are described in [Gateway installation](../docs/en/docs/operate/install-gateway.md#optional-core-target-binding).
5 changes: 3 additions & 2 deletions gateway/crates/pc-gateway-app/src/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub fn load() -> Result<(SocketAddr, Option<String>), &'static str> {
.map_err(|_| "PC_GATEWAY_LISTEN must be an IP address:port")?;
let key = match std::env::var("PC_GATEWAY_API_KEY") {
Ok(value) if !value.is_empty() => Some(value),
Ok(_) | Err(VarError::NotPresent) => None,
Ok(_) => return Err("PC_GATEWAY_API_KEY must be a nonempty Bearer token"),
Err(VarError::NotPresent) => None,
Err(VarError::NotUnicode(_)) => {
return Err("PC_GATEWAY_API_KEY must be a valid Bearer token")
}
Expand Down Expand Up @@ -64,7 +65,7 @@ pub fn authenticate(expected: &str, headers: &HeaderMap) -> bool {
&& bool::from(expected.as_bytes().ct_eq(credential.as_bytes()))
}

fn is_bearer_token(value: &str) -> bool {
pub(crate) fn is_bearer_token(value: &str) -> bool {
// RFC 6750: at least one token character followed by optional '=' padding.
let token = value.trim_end_matches('=');
!token.is_empty()
Expand Down
4 changes: 4 additions & 0 deletions gateway/crates/pc-gateway-app/src/grok_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ async fn magpie_tool_selection_and_identity_survive_checks_and_client_json_or_ss
let canonical =
to_canonical_responses(serde_json::from_value(request).unwrap()).unwrap();
let call = ManagedCall {
target_protocol: "openai-responses".into(),
credential_target: None,
scope_id: "test".into(),
target_profile: "test".into(),
request: canonical,
Expand Down Expand Up @@ -251,6 +253,8 @@ async fn magpie_tool_selection_and_identity_survive_checks_and_client_json_or_ss
block_original.then(|| Bytes::copy_from_slice(reply));
let request = fixture["cases"][0]["request"].clone();
let call = ManagedCall {
target_protocol: "openai-responses".into(),
credential_target: None,
scope_id: "test".into(),
target_profile: "test".into(),
request: to_canonical_responses(serde_json::from_value(request).unwrap()).unwrap(),
Expand Down
Loading
Loading