Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
0a1a0b9
feat: validate gateway account identity and explicit group bindings
ranxi2001 Nov 20, 2026
95d7cd0
Merge remote-tracking branch 'origin/production' into feat/issue959-c…
ranxi2001 Nov 20, 2026
e31ff56
fix: commit gateway settings and group updates atomically
ranxi2001 Nov 20, 2026
cabbf62
Merge remote-tracking branch 'origin/production' into feat/issue959-g…
ranxi2001 Nov 20, 2026
40dbf59
fix: disambiguate gateway account platform constant
ranxi2001 Nov 20, 2026
27b1864
feat: persist request-scoped gateway procurement cost evidence
ranxi2001 Nov 20, 2026
fb1ad20
fix: reserve migration 392 and document observer cost scope
ranxi2001 Nov 20, 2026
a8d88cd
test: keep observer cost projection fixture portable across WS baselines
ranxi2001 Nov 20, 2026
b839f42
ci: retain additive procurement DTO fields in historical cost regress…
ranxi2001 Nov 20, 2026
3e1794e
test: format procurement snapshot fixture columns
ranxi2001 Nov 20, 2026
e45540a
test: align procurement snapshot assertions with gofmt
ranxi2001 Nov 20, 2026
2968092
Merge production and retain gateway identity and probe penalty valida…
ranxi2001 Nov 20, 2026
02601a4
Merge production and preserve gateway and per-model admission checks
ranxi2001 Nov 21, 2026
3752a6a
feat: admit gateway requests into native protocol forwarders
ranxi2001 Nov 21, 2026
435ad71
Merge commit '02601a48a7201e5a01cf359dccff732446d56505' into feat/iss…
ranxi2001 Nov 21, 2026
eed3501
Merge commit '253dc0544dda51a33c1f1a8ca785140d82949f46' into feat/iss…
ranxi2001 Nov 21, 2026
3b7aca9
fix: retain parsed request and model cooldown in relay admission
ranxi2001 Nov 21, 2026
1c1f913
fix: preserve gateway identity through final OpenAI admission
ranxi2001 Nov 21, 2026
9349428
feat: select explicitly bound gateways for native Anthropic messages
ranxi2001 Nov 21, 2026
39aeef6
fix: normalize gateway Anthropic URL and bridge SSE fixture
ranxi2001 Nov 21, 2026
63aa165
fix: normalize gateway Anthropic URL and bridge SSE fixture
ranxi2001 Nov 21, 2026
5efb497
Merge published gateway CI repair 63aa into local scheduling checkpoint
ranxi2001 Nov 21, 2026
4394bd9
fix: retain selection model during gateway channel admission
ranxi2001 Nov 21, 2026
62f3e20
Merge commit 'a25b88dd8846d39b71f39ebf5877e5c1c4194aca' into feat/iss…
ranxi2001 Nov 21, 2026
5e26043
Merge commit '8e7a233de' into HEAD
ranxi2001 Nov 21, 2026
a01e875
fix: 复用网关读取事务并修复 Messages 调度回归夹具
ranxi2001 Nov 21, 2026
44ecd22
feat: 接入跨平台网关账号表单、分组选择和上游余额查询
ranxi2001 Nov 21, 2026
287cb38
feat: 按请求协议选择已入组网关并在转发前复核账号
ranxi2001 Nov 21, 2026
93b65e4
feat: 在区域快照内验证网关授权并及时应用撤组
ranxi2001 Nov 21, 2026
843b33c
Merge production and retain both historical fixture entries
ranxi2001 Nov 21, 2026
e093840
fix: 修复网关模型发现、渠道映射准入、区域续接与声明成本
ranxi2001 Nov 21, 2026
7e66c30
fix: 保留网关手工采购成本并按公开别名检查 Composite 目录
ranxi2001 Nov 21, 2026
00a31e3
fix: 按 Composite 实际命中的路由验证模型目录
ranxi2001 Nov 21, 2026
c13d881
fix: 为 Gemini fresh admission 拒绝返回安全错误响应
ranxi2001 Nov 21, 2026
11bb4eb
Merge production cooldown repair into PR971 maintenance
ranxi2001 Nov 21, 2026
f1cdb7a
fix: 隔离历史 RED 中的 Gemini 网关回归夹具
ranxi2001 Nov 21, 2026
de68d26
Merge production billing admission repair into PR971 maintenance
ranxi2001 Nov 21, 2026
9498149
style: 对齐账务恢复回归快照字段
ranxi2001 Nov 21, 2026
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
7 changes: 6 additions & 1 deletion .github/scripts/prepare-image-usage-free-fast-red.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
marker = 'type UsageLog struct {'
# Omit nil just as the pre-snapshot DTO did; persistence RED must reach
# its original missing-snapshot assertion, not a later JSON null mismatch.
addition = '\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n'
addition = ('\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n'
'\tProcurementCostSnapshot *ProcurementCostSnapshot `json:"ProcurementCostSnapshot,omitempty"`\n')
elif phase == 'admin-usage':
name = 'backend/internal/handler/dto/types.go'
marker = 'type AdminUsageLog struct {'
addition = '\n\tProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"`\n'
elif phase == 'cache':
name = 'backend/internal/service/customer_cost_details.go'
marker = 'type CustomerCostDetails struct {'
Expand Down
7 changes: 7 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,13 @@ backend/internal/handler/request_body_read_log_test.go
backend/internal/handler/probe_penalty_response_test.go
backend/internal/service/account_probe_penalty_test.go

# Native Messages gateway selection requires the request-scoped account and group reader.
backend/internal/handler/gateway_messages_selection_test.go

# Native Gemini envelope tests share those candidate-only gateway APIs/fixtures.
# Frozen candidate blob: 2aeba94f1e98e3db91b6d3006ed0d0575775a6e9; full historical RED only.
backend/internal/handler/gateway_gemini_envelope_test.go

# Model plaza display currency tests require the candidate display configuration.
backend/internal/service/model_plaza_currency_test.go
backend/internal/service/model_plaza_currency_update_test.go
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/free-fast-customer-cost-details.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ jobs:
# The new image receipt reader needs the additive DTO field; retain
# the old Free Fast producer so the selected assertions still fail.
python3 .github/scripts/prepare-image-usage-free-fast-red.py usage "$baseline"
python3 .github/scripts/prepare-image-usage-free-fast-red.py admin-usage "$baseline"
# Tests stay byte-for-byte at candidate HEAD. Keep the new additive
# DB column so a missing migration can never qualify as business RED.
set +e
Expand Down
67 changes: 64 additions & 3 deletions .github/workflows/issue959-gateway-regression.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ on:
paths:
- 'backend/internal/domain/constants.go'
- 'backend/internal/service/**'
- 'backend/internal/handler/admin/account*'
- 'backend/internal/handler/dto/account_mapper_redact_test.go'
- 'backend/internal/repository/account_repo.go'
- 'backend/internal/repository/group_repo.go'
- 'backend/internal/repository/gateway_account*'
- 'backend/internal/repository/gateway_request_admission*'
- 'backend/internal/repository/gateway_request_candidates*'
- 'backend/internal/handler/gateway_messages_selection_test.go'
- 'backend/internal/handler/gateway_gemini_envelope_test.go'
- 'backend/internal/handler/gemini_v1beta_handler.go'
- 'backend/internal/repository/oauth_degradation_group_bindings*'
- 'backend/internal/repository/procurement_cost_snapshot*'
- 'backend/internal/repository/profit_operations.go'
- 'backend/internal/repository/usage_log_repo*'
- 'backend/internal/handler/dto/procurement_cost_snapshot*'
- 'backend/internal/handler/usage_observer_test.go'
- 'backend/migrations/392_usage_procurement_cost_snapshot.sql'
- 'backend/internal/repository/concurrency_cache*'
- 'backend/internal/repository/integration_harness_test.go'
- 'backend/go.mod'
Expand Down Expand Up @@ -66,27 +83,71 @@ jobs:
shell: bash
run: |
set -euo pipefail
go test -race -tags=unit ./internal/service \
-run '^Test(GatewayIdentity|GatewayUsage|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots)' \
go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin ./internal/handler/dto ./internal/repository \
-run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then
exit 1
fi
grep -F -- '--- PASS: TestGatewayUsageWritersSnapshotRequestTarget' ../evidence/unit-race.log
grep -F -- '--- PASS: TestNewAPIGatewayCostsFollowRequestTargetWithoutSharedWrites' ../evidence/unit-race.log
grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolOpenAIAuthoritativeAdmission' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolOpenAIResponsesMappedWireModel' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidatesStayRequestScoped' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolMessagesHandlerSchedulerToUsage' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolMessagesChannelMappingPreservesBindingModel' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolGeminiFreshAdmissionErrorEnvelope' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolGeminiForwardErrorResponseOwnership' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log
grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log
grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log
grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log
grep -F -- '--- PASS: TestObserverProcurementSnapshotFollowsExistingAccountCostScope' ../evidence/unit-race.log
- name: Shared account slots against isolated Redis
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=integration ./internal/repository \
-run '^TestConcurrencyCacheSuite$/^TestGatewayTargetsShareAccountConcurrency$' \
-run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion|RequestAdmissionReloadsGroupMembershipAndStatus|RequestCandidatesRequireLiveExplicitAnthropicGroup)|admin|account-service|bulk)$' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then
exit 1
fi
grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestCandidatesRequireLiveExplicitAnthropicGroup' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestGatewayAtomicUpdateOAuthInterleaving' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log
grep -F -- '--- PASS: TestGatewayAtomicUpdateCallerTransactionRollback' ../evidence/concurrency-redis.log
- name: Procurement snapshots and legacy profit accounting
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=integration ./internal/repository \
-run '^(TestProcurementSnapshot|TestProfitOperationsPersistedProfitIndependentFromAccountDebit|TestProfitOperationsZeroLossUnknownAndCurrentConfiguration)' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/procurement-cost.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/procurement-cost.log; then
exit 1
fi
grep -F -- '--- PASS: TestProcurementSnapshotAllInsertPathsAndImmutability' ../evidence/procurement-cost.log
grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log
grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log
grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log
- uses: actions/upload-artifact@v7
if: always()
with:
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/domain/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ const (
PlatformComposite = "composite"
)

// AccountPlatformGateway is an account-only identity, never a request or group platform.
const AccountPlatformGateway = "gateway"

// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
// 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。
const (
Expand Down
5 changes: 4 additions & 1 deletion backend/internal/handler/admin/account_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,9 @@ func validateDataProxy(item DataProxy) error {
}

func validateDataAccount(item DataAccount) error {
if err := service.ValidateGatewayAccountIdentity(item.Platform, item.Type, item.Credentials); err != nil {
return err
}
if strings.TrimSpace(item.Name) == "" {
return errors.New("account name is required")
}
Expand All @@ -843,7 +846,7 @@ func validateDataAccount(item DataAccount) error {
return errors.New("account credentials is required")
}
switch item.Type {
case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream:
case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream, service.AccountTypeGateway:
default:
return fmt.Errorf("account type is invalid: %s", item.Type)
}
Expand Down
24 changes: 24 additions & 0 deletions backend/internal/handler/admin/account_gateway_data_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package admin

import (
"testing"

"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/require"
)

func TestGatewayDataImportIdentityValidation(t *testing.T) {
item := DataAccount{Name: "Gateway import fixture", Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
Credentials: map[string]any{"upstream_kind": "sub2api", "base_url": "https://import.example", "api_key": "synthetic-key"}}
require.NoError(t, validateDataAccount(item))
require.NoError(t, binding.Validator.ValidateStruct(CreateAccountRequest{Name: item.Name, Platform: item.Platform, Type: item.Type, Credentials: item.Credentials}))
require.NoError(t, binding.Validator.ValidateStruct(UpdateAccountRequest{Type: item.Type}))
item.Platform = service.PlatformOpenAI
require.Error(t, validateDataAccount(item))
item.Platform = service.PlatformGateway
item.Credentials["upstream_kind"] = "unknown"
require.Error(t, validateDataAccount(item))
item.Type = service.AccountTypeAPIKey
require.Error(t, validateDataAccount(item))
}
4 changes: 2 additions & 2 deletions backend/internal/handler/admin/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ type CreateAccountRequest struct {
Name string `json:"name" binding:"required"`
Notes *string `json:"notes"`
Platform string `json:"platform" binding:"required"`
Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account"`
Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account gateway"`
Credentials map[string]any `json:"credentials" binding:"required"`
Extra map[string]any `json:"extra"`
ProxyID *int64 `json:"proxy_id"`
Expand All @@ -170,7 +170,7 @@ type UpdateAccountRequest struct {
Platform string `json:"platform"`
Name string `json:"name"`
Notes *string `json:"notes"`
Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account"`
Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account gateway"`
Credentials map[string]any `json:"credentials"`
Extra map[string]any `json:"extra"`
ProxyID *int64 `json:"proxy_id"`
Expand Down
11 changes: 11 additions & 0 deletions backend/internal/handler/dto/account_mapper_redact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)

func TestAccountGatewayDTORedactsCallingKey(t *testing.T) {
account := &service.Account{Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-gateway-secret"}}
got := AccountFromServiceShallow(account)
require.Equal(t, "new_api", got.Credentials["upstream_kind"])
require.True(t, got.CredentialsStatus["has_api_key"])
raw, err := json.Marshal(got)
require.NoError(t, err)
require.NotContains(t, string(raw), "synthetic-gateway-secret")
}

func TestAccountFromServiceShallow_RedactsSensitiveCredentials(t *testing.T) {
src := &service.Account{
ID: 42,
Expand Down
1 change: 1 addition & 0 deletions backend/internal/handler/dto/mappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,7 @@ func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog {
BillingTier: l.BillingTier,
AccountRateMultiplier: l.AccountRateMultiplier,
AccountStatsCost: l.AccountStatsCost,
ProcurementCostSnapshot: l.ProcurementCostSnapshot,
IPAddress: l.IPAddress,
Account: AccountSummaryFromService(l.Account),
}
Expand Down
23 changes: 23 additions & 0 deletions backend/internal/handler/dto/procurement_cost_snapshot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package dto

import (
"encoding/json"
"testing"

"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)

func TestProcurementSnapshotAdminDTOAndUserPrivacy(t *testing.T) {
factor := .7
log := &service.UsageLog{TotalCost: 10, ActualCost: 3, ProcurementCostSnapshot: &service.ProcurementCostSnapshot{
Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: "openai", Basis: "total_cost", CostMultiplier: &factor}}
admin, err := json.Marshal(UsageLogFromServiceAdmin(log))
require.NoError(t, err)
require.Contains(t, string(admin), `"procurement_cost_snapshot"`)
require.Contains(t, string(admin), `"cost_multiplier":0.7`)
user, err := json.Marshal(UsageLogFromService(log))
require.NoError(t, err)
require.NotContains(t, string(user), "procurement_cost_snapshot")
require.Nil(t, UsageLogFromServiceAdmin(&service.UsageLog{}).ProcurementCostSnapshot)
}
2 changes: 2 additions & 0 deletions backend/internal/handler/dto/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,8 @@ type AdminUsageLog struct {
AccountRateMultiplier *float64 `json:"account_rate_multiplier"`
// AccountStatsCost 自定义定价规则计算的账号统计费用(nil 表示使用默认公式)
AccountStatsCost *float64 `json:"account_stats_cost,omitempty"`
// ProcurementCostSnapshot follows existing admin/authorized observer cost scope.
ProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"`

// IPAddress 用户请求 IP
IPAddress *string `json:"ip_address,omitempty"`
Expand Down
Loading
Loading