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
29 changes: 29 additions & 0 deletions .github/workflows/bps-wire-contract.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: BPS request contract
on:
pull_request:
paths:
- 'backend/internal/service/basispoints/**'
- 'backend/internal/service/openai_excel_bps*'
- 'backend/internal/service/openai_gateway_request_body.go'
- '.github/workflows/bps-wire-contract.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
contract:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: BPS wire contract and existing protocol regressions
working-directory: backend
run: go test ./internal/service/basispoints -count=1
- name: Gateway identity, model, effort, tier policy and correction
working-directory: backend
run: go test -tags=unit ./internal/service -run '^Test(ExcelBPSWire|ExcelBPSToolCorrectionPreservesRouteAndUsage|ExcelBPSUsagePreservesRequestedEffortBeforeGroupMapping|ExcelBPSAccess)' -count=1 -v -timeout=10m
5 changes: 4 additions & 1 deletion backend/internal/service/basispoints/basispoints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,14 @@ func TestPrepareWireShapeAndDeterminism(t *testing.T) {
if entry["type"] != "compaction" || fmt.Sprint(entry["compact_threshold"]) != "920000" {
t.Fatalf("unexpected default compaction threshold: %+v", entry)
}
for _, field := range []string{"tools", "reasoning", "include", "service_tier", "instructions"} {
for _, field := range []string{"tools", "reasoning", "include", "instructions"} {
if _, exists := first[field]; exists {
t.Fatalf("unsupported field leaked: %s", field)
}
}
if first["service_tier"] != "priority" {
t.Fatal("explicit priority tier must reach BPS")
}
other, _ := mustPrepare(t, source, "account-2/key-1", nil)
if first["prompt_cache_key"] == other["prompt_cache_key"] {
t.Fatal("cache routing must be scoped by account and client")
Expand Down
20 changes: 20 additions & 0 deletions backend/internal/service/basispoints/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,23 @@ func prepareWithInheritedCatalog(raw []byte, scope string, replay *ReplayCache,
if text(source["previous_response_id"]) != "" {
return nil, nil, fmt.Errorf("basispoints requires expanded history instead of previous_response_id")
}
// Preserve explicit processing tier instead of silently dropping the client's
// selection. BPS supports this narrower set; do not invent an upgrade.
serviceTier := ""
if value, exists := source["service_tier"]; exists && value != nil {
tier, ok := value.(string)
if !ok {
return nil, nil, fmt.Errorf("basispoints service_tier must be a string")
}
switch strings.ToLower(strings.TrimSpace(tier)) {
case "auto", "default", "priority":
serviceTier = strings.ToLower(strings.TrimSpace(tier))
case "fast":
serviceTier = "priority"
default:
return nil, nil, fmt.Errorf("basispoints service_tier must be auto, default or priority")
}
}
requested := text(source["reasoning_effort"])
if reasoning, ok := source["reasoning"].(object); ok {
requested = text(reasoning["effort"])
Expand Down Expand Up @@ -237,6 +254,9 @@ func prepareWithInheritedCatalog(raw []byte, scope string, replay *ReplayCache,
"turn_id": fingerprint([]any{scope, input[:turnEnd]}), "agent_iteration": fmt.Sprint(iteration),
},
}
if serviceTier != "" {
output["service_tier"] = serviceTier
}
if cacheKey != "" {
output["prompt_cache_key"] = "bps-" + fingerprint([]any{scope, cacheKey})
}
Expand Down
66 changes: 66 additions & 0 deletions backend/internal/service/basispoints/service_tier_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package basispoints

import (
"encoding/json"
"testing"
)

func TestBPSServiceTierWireContract(t *testing.T) {
for _, tc := range []struct {
name string
input any
present bool
want string
invalid bool
}{
{name: "missing"}, {name: "null", present: true},
{name: "priority", present: true, input: "priority", want: "priority"},
{name: "fast alias", present: true, input: " Fast ", want: "priority"},
{name: "auto", present: true, input: "auto", want: "auto"},
{name: "default", present: true, input: "default", want: "default"},
{name: "unknown", present: true, input: "private-tier", invalid: true},
{name: "flex", present: true, input: "flex", invalid: true},
{name: "object", present: true, input: object{"token": "must-not-echo"}, invalid: true},
{name: "empty", present: true, input: "", invalid: true},
} {
t.Run(tc.name, func(t *testing.T) {
source := testSource()
if tc.present {
source["service_tier"] = tc.input
}
raw, _ := json.Marshal(source)
body, bridge, err := Prepare(raw, "fixture", nil)
if tc.invalid {
if err == nil {
t.Fatal("unsupported tier accepted")
}
return
}
if err != nil {
t.Fatal(err)
}
var wire object
if err = json.Unmarshal(body, &wire); err != nil {
t.Fatal(err)
}
if text(wire["service_tier"]) != tc.want {
t.Fatalf("tier=%v want %q", wire["service_tier"], tc.want)
}
if tc.want == "" {
if _, ok := wire["service_tier"]; ok {
t.Fatal("missing tier must remain absent")
}
}
body, _, err = bridge.Reprepare(raw)
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(body, &wire); err != nil {
t.Fatal(err)
}
if text(wire["service_tier"]) != tc.want {
t.Fatal("Reprepare lost tier")
}
})
}
}
23 changes: 22 additions & 1 deletion backend/internal/service/openai_excel_bps.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,15 @@ func newExcelBPSRequestTo(ctx context.Context, targetURL, accept string, body []
"X-Openai-Internal-Basispoints-Client-Product": {"basispoints-excel-plugin"},
"X-Openai-Internal-Basispoints-Client-Agent-Profile": {"excel"},
}
// Derive the user only from the bearer actually sent on this request. The
// parent account can retain a different Codex grant or stale user metadata.
// Decoding projects identity; it does not assert JWT signature validation.
if claims, decodeErr := openai.DecodeIDToken(token); decodeErr == nil && claims.OpenAIAuth != nil {
userID := strings.TrimSpace(firstNonEmptyReauth(claims.OpenAIAuth.ChatGPTUserID, claims.OpenAIAuth.UserID))
if userID != "" && !strings.ContainsAny(userID, "\r\n") {
req.Header.Set("X-Openai-Account-User-Id", userID)
}
}
return req, nil
}

Expand Down Expand Up @@ -278,6 +287,17 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte
}
return nil, newExcelBPSRateLimitedFailoverError(retryAfter)
}
// BPS returns before the native forwarder's tier policy. Apply that same
// administrator policy before building the BPS wire body.
body, err := s.applyOpenAIFastPolicyToBody(ctx, account, model, body)
if err != nil {
var blocked *OpenAIFastBlockedError
if errors.As(err, &blocked) {
MarkResponseCommitted(c)
writeOpenAIFastPolicyBlockedResponse(c, blocked)
}
return nil, err
}
imageSettings, err := s.settingService.GetExcelBPSImageRelaySettings(ctx)
if err != nil {
if isExcelBPSClientCancellation(c, err) {
Expand Down Expand Up @@ -818,7 +838,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte
// The bridge sees the body after group policy mapping. Keep the original
// client effort for usage display, and the BPS-normalized effort for billing.
requestedEffort := coalesceRequestedReasoningEffort(RequestedReasoningEffortFromContext(ctx), &bridge.RequestedEffort)
result := &OpenAIForwardResult{Model: originalModel, UpstreamModel: model, UpstreamEndpoint: "/basispoints/api/responses", Stream: stream, ReasoningEffort: &bridge.Effort, RequestedReasoningEffort: requestedEffort, RequestID: resp.Header.Get("x-request-id")}
result := &OpenAIForwardResult{Model: originalModel, UpstreamModel: model, UpstreamEndpoint: "/basispoints/api/responses", Stream: stream, ReasoningEffort: &bridge.Effort, RequestedReasoningEffort: requestedEffort, ServiceTier: extractOpenAIServiceTierFromBody(upstreamBody), RequestID: resp.Header.Get("x-request-id")}
if stream {
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
Expand Down Expand Up @@ -874,6 +894,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte
completed = []byte(gjson.GetBytes(payload, "response").Raw)
result.ResponseID = gjson.GetBytes(payload, "response.id").String()
result.UpstreamResponseModel = gjson.GetBytes(payload, "response.model").String()
result.UpstreamResponseServiceTier = normalizeObservedOpenAIServiceTier(gjson.GetBytes(payload, "response.service_tier").String())
upstreamFailure = basispoints.ParseUpstreamFailure(payload)
if bridgeFailure != nil {
markPriorityAttemptFailure(ctx)
Expand Down
3 changes: 2 additions & 1 deletion backend/internal/service/openai_excel_bps_repair_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func TestExcelBPSToolCorrectionPreservesRouteAndUsage(t *testing.T) {
}
svc := openAIClientToolsTestService(upstream)
svc.httpUpstream = checked
body := []byte(fmt.Sprintf(`{"model":"gpt-5.6-sol","stream":%t,"reasoning":{"effort":"max"},"input":"test correction","tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"exec"}]}]}`, stream))
body := []byte(fmt.Sprintf(`{"model":"gpt-5.6-sol","stream":%t,"reasoning":{"effort":"max"},"input":"test correction","service_tier":"priority","tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"exec"}]}]}`, stream))
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
Expand Down Expand Up @@ -112,6 +112,7 @@ func TestExcelBPSToolCorrectionPreservesRouteAndUsage(t *testing.T) {
require.True(t, checked.bodies[i].closed.Load())
require.Equal(t, "gpt-5.6-sol", gjson.GetBytes(upstream.bodies[i], "model").String())
require.Equal(t, "xhigh", gjson.GetBytes(upstream.bodies[i], "reasoning_effort").String())
require.Equal(t, "priority", gjson.GetBytes(upstream.bodies[i], "service_tier").String())
require.False(t, gjson.GetBytes(upstream.bodies[i], "tools").Exists())
require.Equal(t, fmt.Sprint(i+1), gjson.GetBytes(upstream.bodies[i], "metadata.agent_iteration").String())
require.Equal(t, gjson.GetBytes(upstream.bodies[0], "metadata.task_id").String(), gjson.GetBytes(upstream.bodies[i], "metadata.task_id").String())
Expand Down
125 changes: 125 additions & 0 deletions backend/internal/service/openai_excel_bps_wire_contract_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package service

import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/service/basispoints"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)

func bpsWireToken(t *testing.T, auth map[string]string) string {
t.Helper()
payload, err := json.Marshal(map[string]any{"sub": "not-an-account-user", "https://api.openai.com/auth": auth})
require.NoError(t, err)
return "header." + base64.RawURLEncoding.EncodeToString(payload) + ".signature"
}

func TestExcelBPSWireIdentityUsesActualBearer(t *testing.T) {
for _, tc := range []struct {
name string
auth map[string]string
want string
}{
{"account user", map[string]string{"chatgpt_user_id": "bps-user", "user_id": "other"}, "bps-user"},
{"user fallback", map[string]string{"user_id": "bps-user"}, "bps-user"},
{"missing user does not use sub", map[string]string{}, ""},
{"invalid header", map[string]string{"user_id": "bad\r\nInjected: value"}, ""},
} {
t.Run(tc.name, func(t *testing.T) {
for _, endpoint := range []string{basispoints.ResponsesURL, basispoints.ImagesGenerationsURL, "https://bps.openai.com/basispoints/api/attachments", "https://bps.openai.com/basispoints/api/responses/access?include_models=true"} {
token := bpsWireToken(t, tc.auth)
req, err := newExcelBPSRequestTo(context.Background(), endpoint, "application/json", nil, token, "fixture-workspace")
require.NoError(t, err)
require.Equal(t, tc.want, req.Header.Get("X-Openai-Account-User-Id"))
require.Equal(t, "Bearer "+token, req.Header.Get("Authorization"))
require.Equal(t, "fixture-workspace", req.Header.Get("X-Openai-Account-Id"))
require.Empty(t, req.Header.Get("Cookie"))
}
})
}
req, err := newExcelBPSRequest(context.Background(), nil, "opaque-token", "fixture-workspace")
require.NoError(t, err)
require.Empty(t, req.Header.Get("X-Openai-Account-User-Id"))
}

func TestExcelBPSWireTierPolicyAndModelEvidence(t *testing.T) {
for _, tc := range []struct {
name, tier, action, want string
force bool
status int
}{
{name: "priority", tier: "priority", want: "priority"},
{name: "fast alias", tier: "fast", want: "priority"},
{name: "default", tier: "default", want: "default"},
{name: "auto", tier: "auto", want: "auto"},
{name: "missing stays missing"},
{name: "group force", force: true, want: "priority"},
{name: "filter overrides group", force: true, action: BetaPolicyActionFilter},
{name: "block", tier: "priority", action: BetaPolicyActionBlock, status: 403},
{name: "unsupported is not silently dropped", tier: "flex", status: 400},
} {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/stream=%t", tc.name, stream), func(t *testing.T) {
settings := DefaultOpenAIFastPolicySettings()
if tc.action != "" {
settings.Rules = []OpenAIFastPolicyRule{{ServiceTier: OpenAIFastTierPriority, Action: tc.action, Scope: BetaPolicyScopeAll, FallbackAction: BetaPolicyActionPass}}
}
svc := openAIClientToolsTestService(nil)
svc.settingService = newOpenAIGatewayServiceWithSettings(t, settings).settingService
wire := "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_wire\",\"status\":\"completed\",\"model\":\"gpt-5.6-luna\",\"service_tier\":\"default\",\"output\":[],\"usage\":{\"input_tokens\":10,\"output_tokens\":2}}}\n\n"
upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(wire))}}
svc.httpUpstream = upstream
input := map[string]any{"model": "public-astra", "stream": stream, "reasoning": map[string]any{"effort": "xhigh"}, "input": "fixture request"}
if tc.tier != "" {
input["service_tier"] = tc.tier
}
body, err := json.Marshal(input)
require.NoError(t, err)
account := excelAccount()
account.Credentials["model_mapping"] = map[string]any{"public-astra": "gpt-6-astra"}
account.Credentials["access_token"] = bpsWireToken(t, map[string]string{"chatgpt_account_id": "test-account", "user_id": "selected-bps-user"})
account.Credentials["chatgpt_user_id"] = "stale-codex-user"
ctx := context.Background()
if tc.force {
ctx = context.WithValue(ctx, ctxkey.Group, &Group{ID: 7, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true, ForceOpenAIFast: true})
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest("POST", "/v1/responses", bytes.NewReader(body)).WithContext(ctx)
c.Request.Header.Set("X-Openai-Account-User-Id", "untrusted-client-user")
result, err := svc.Forward(ctx, c, account, body)
if tc.status != 0 {
require.Error(t, err)
require.Equal(t, tc.status, rec.Code)
require.Empty(t, upstream.requests)
return
}
require.NoError(t, err)
require.NotNil(t, result)
require.Len(t, upstream.requests, 1)
require.Equal(t, "gpt-6-astra", gjson.GetBytes(upstream.lastBody, "model").String())
require.Equal(t, "explicit", gjson.GetBytes(upstream.lastBody, "model_selection").String())
require.Equal(t, "xhigh", gjson.GetBytes(upstream.lastBody, "reasoning_effort").String())
require.Equal(t, tc.want, gjson.GetBytes(upstream.lastBody, "service_tier").String())
require.Equal(t, tc.want, optionalStringValue(result.ServiceTier))
require.Equal(t, "selected-bps-user", upstream.lastReq.Header.Get("X-Openai-Account-User-Id"))
require.Equal(t, "gpt-5.6-luna", result.UpstreamResponseModel, "never relabel provider model as requested Astra")
require.Equal(t, "default", result.UpstreamResponseServiceTier, "keep provider declaration distinct from requested priority")
require.Contains(t, rec.Body.String(), "gpt-5.6-luna")
require.Equal(t, "gpt-6-astra", result.UpstreamModel)
})
}
}
}
10 changes: 10 additions & 0 deletions docs/excel-bps.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,13 @@ python backend/scripts/e2e-bps-ignore-images.py --expect ignore --stream --outpu
- 两个账号测试弹窗都会显示模型目录加载失败原因、重新加载按钮和凭据运维入口。部分模型走 BPS 时,仅保留从原生目录取得、且配置为原生路由的模型,不用原生能力冒充 BPS 能力。

没有数据库迁移,新增 Extra 中的 `openai_excel_bps_authorization_pending` 运行态标记。回退旧二进制前应先关闭仍在准备中的 BPS 开关:旧版本不识别该标记,会立即尝试 BPS;已经保存的 Excel 授权不会因回滚撤销。上线验收仍需用获准的账号分别确认模型目录和一次最小生成请求;离线测试不能证明上游登录安全验证已经解除。

## CPA 0.5.31 请求契约对齐(#812)

BPS 请求现在从**本次实际发送的 bearer**中提取 `chatgpt_user_id` / `user_id`,补充 `X-Openai-Account-User-Id`。不使用客户端传入的同名头,也不以父账号可能保留的 Codex 用户字段覆盖 Excel grant;无法提取时保持该头缺省。JWT 解码用于投影已选凭据的身份,不表示本地完成签名验证。

Responses 的 `service_tier` 在 BPS 路径沿用既有管理员 Fast 策略:可过滤、拒绝或按已有分组设置强制 priority;过滤/拒绝不会被 BPS 转换重新开启。转换支持 `auto`、`default`、`priority`,`fast` 归一为 `priority`,缺省/null 不主动升级;其他值返回 400,避免静默丢失选择。只在调用者明确指定或管理员已有配置要求时发送 priority,其费用影响沿用现有服务层级计费策略。记录最终发送层级和上游终态声明层级,二者分别保存。

模型映射后的真实 model、`model_selection=explicit`、xhigh 等现有强度、授权身份在工具修正请求中保持一致。上游声明的 Luna 等模型仍如实传回并记录,不能改名成请求的 Astra。目录 allowed、HTTP 200、priority、请求模型保持均不能独立证明模型能力或 Team 二轮账号“不降智”。

实现依据是固定 CPA/BPS 0.5.31 发布物的静态请求契约,[核验与差异记录见 #812](https://github.com/ranxi2001/sub2api/issues/812),使用现有原生 Go adapter 独立实现,没有加载第三方二进制或复制打包源码。CI 使用虚构 token 和假上游验证请求/响应及管理员策略;真实二轮账号、质量题组和长期保持能力尚未验收。本改动无数据库迁移,也未新增默认 Fast 开关。
Loading