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
471 changes: 471 additions & 0 deletions .github/scripts/gateway-models-ui.mjs

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions .github/scripts/pr838-ui-build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ import { pathToFileURL } from 'node:url'

const repo = resolve('.'), output = process.env.EVIDENCE_DIR
if (!output || process.env.GITHUB_ACTIONS !== 'true') throw Error('Isolated CI only')
const baselineRoot = resolve(process.env.BASELINE_FRONTEND_ROOT || '.pr838-baseline/frontend')
const noticeKeys = process.env.EVIDENCE_SCENARIO === 'gateway-models'
? { A: 'crossPlatformGatewayAccounts', B: 'gatewayModelSync', C: 'fixture-gateway-models-future-announcement-C' }
: { A: 'vipAutoCredit', B: 'tempUnschedStreamCountWindow', C: 'fixture-pr838-future-announcement-C' }
mkdirSync(output, { recursive: true })
const { build } = await import(pathToFileURL(join(repo, 'frontend/node_modules/vite/dist/node/index.js')))
for (const mode of ['before', 'after']) {
const root = join(repo, mode === 'before' ? '.pr838-baseline/frontend' : 'frontend')
const root = mode === 'before' ? baselineRoot : join(repo, 'frontend')
const extra = join(root, 'pr838-notices.html'), entry = join(root, '.pr838-notices.js')
try {
if (mode === 'after') {
Expand All @@ -22,7 +26,9 @@ import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';import '/src/style.cs
async function mountNotices(){
await loadLocaleMessages('en');i18n.global.locale.value='en';
// Future C is deliberately a test-only registered ID, not a product announcement.
const registry={A:ids.vipAutoCredit,B:ids.tempUnschedStreamCountWindow,C:'fixture-pr838-future-announcement-C'};
const keys=${JSON.stringify(noticeKeys)};
const registry={A:ids[keys.A],B:ids[keys.B],C:keys.C};
if(!registry.A||!registry.B)throw Error('Requested notice IDs must exist in the actual candidate registry');
const p=new URLSearchParams(location.search), phase=p.get('phase')||'a',user=Number(p.get('user'));
if(!Number.isSafeInteger(user)||user<1)throw Error('Fictional fixture administrator required');
const entries=phase==='a'?['A']:phase==='b'?['A','B','B']:['A','B','B','C'];
Expand Down
16 changes: 15 additions & 1 deletion .github/workflows/issue959-gateway-regression.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ on:
- 'backend/internal/handler/admin/account*'
- 'backend/internal/handler/dto/account_mapper_redact_test.go'
- 'backend/internal/repository/account_repo.go'
- 'backend/internal/repository/account_repo_upstream_model_sync*'
- 'backend/internal/repository/group_repo.go'
- 'backend/internal/repository/gateway_account*'
- 'backend/internal/repository/gateway_request_admission*'
Expand Down Expand Up @@ -84,7 +85,7 @@ jobs:
run: |
set -euo pipefail
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)' \
-run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayUpstreamModels|AccountHandlerGatewayModels|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
Expand All @@ -94,6 +95,9 @@ jobs:
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: TestGatewayUpstreamModelsDiscoveryAndApply' ../evidence/unit-race.log
grep -F -- '--- PASS: TestAccountHandlerGatewayModelsDraftAndSavedConnection' ../evidence/unit-race.log
grep -F -- '--- PASS: TestGatewayProtocolCatalogSavedModelsAndGroupPrecedence' ../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
Expand Down Expand Up @@ -148,6 +152,16 @@ jobs:
grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log
grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log
grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log
- name: Gateway account-only model persistence
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=integration ./internal/repository \
-run '^Test(GatewayUpstreamModelsPersistOnlyAccountMapping|ApplyUpstreamModelsPreservesCredentialsAndInvalidatesScheduler)$' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/gateway-model-persistence.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/gateway-model-persistence.log; then exit 1; fi
grep -F -- '--- PASS: TestGatewayUpstreamModelsPersistOnlyAccountMapping' ../evidence/gateway-model-persistence.log
- uses: actions/upload-artifact@v7
if: always()
with:
Expand Down
134 changes: 133 additions & 1 deletion .github/workflows/pr838-ui-acceptance.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
name: PR838 isolated administration acceptance
on:
workflow_dispatch:
inputs:
scenario:
type: choice
options: [pr838, gateway-models]
default: gateway-models
description: Actual application acceptance scenario
candidate:
type: string
required: true
description: Exact candidate commit SHA (must match the dispatched workflow ref)
pull_request:
branches: [production]
paths:
- 'frontend/src/components/account/**'
- 'frontend/src/stores/newFeatureNotices.ts'
- '.github/fixtures/pr838-ui/**'
- '.github/scripts/pr838-ui-*.mjs'
- '.github/scripts/gateway-models-ui.mjs'
- '.github/workflows/pr838-ui-acceptance.yml'
permissions:
contents: read
Expand All @@ -15,10 +27,11 @@ concurrency:
cancel-in-progress: true
jobs:
administration:
if: github.event_name == 'pull_request' || inputs.scenario == 'pr838'
runs-on: ubuntu-24.04
timeout-minutes: 40
env:
CANDIDATE: ${{ github.event.pull_request.head.sha }}
CANDIDATE: ${{ github.event.pull_request.head.sha || inputs.candidate }}
# Full production frontend before this feature; never overlay components.
BASELINE: b347249687db84dac3f5272189fda6cf86eb9035
steps:
Expand Down Expand Up @@ -114,3 +127,122 @@ jobs:
${{ runner.temp }}/pr838-ui/*.png
if-no-files-found: error
retention-days: 30

gateway-models:
if: github.event_name == 'workflow_dispatch' && inputs.scenario == 'gateway-models'
runs-on: ubuntu-24.04
timeout-minutes: 35
env:
CANDIDATE: ${{ inputs.candidate }}
BASELINE: c76d8d3de146408e35b79814955088b355c66135
EVIDENCE_SCENARIO: gateway-models
NODE_OPTIONS: --max-old-space-size=6144
steps:
- name: Require immutable candidate from the selected workflow revision
env:
WORKFLOW_SHA: ${{ github.sha }}
run: |
set -euo pipefail
[[ "$CANDIDATE" =~ ^[0-9a-f]{40}$ ]]
test "$CANDIDATE" = "$WORKFLOW_SHA"
- uses: actions/checkout@v6
with:
ref: ${{ env.CANDIDATE }}
fetch-depth: 0
persist-credentials: false
- uses: actions/checkout@v6
with:
ref: ${{ env.BASELINE }}
path: .gateway-models-baseline
persist-credentials: false
- uses: pnpm/action-setup@v6
with:
version: 9
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Configure isolated evidence and verify original source trees
run: |
set -euo pipefail
printf 'EVIDENCE_DIR=%s/gateway-models-evidence\n' "$RUNNER_TEMP" >> "$GITHUB_ENV"
printf 'BASELINE_FRONTEND_ROOT=%s/.gateway-models-baseline/frontend\n' "$GITHUB_WORKSPACE" >> "$GITHUB_ENV"
printf 'SUB2API_PLAYWRIGHT_MODULE=%s/gateway-models-browser/node_modules/playwright/index.mjs\n' "$RUNNER_TEMP" >> "$GITHUB_ENV"
test "$(git rev-parse HEAD)" = "$CANDIDATE"
test "$(git -C .gateway-models-baseline rev-parse HEAD)" = "$BASELINE"
cmp frontend/package.json .gateway-models-baseline/frontend/package.json
cmp frontend/pnpm-lock.yaml .gateway-models-baseline/frontend/pnpm-lock.yaml
- name: Prepare locked frontend and isolated browser on remote runner only
run: |
set -euo pipefail
mkdir -p "$EVIDENCE_DIR"
git rev-parse HEAD > "$EVIDENCE_DIR/candidate.txt"
git -C .gateway-models-baseline rev-parse HEAD > "$EVIDENCE_DIR/baseline.txt"
pnpm --dir frontend install --frozen-lockfile
npm install --prefix "$RUNNER_TEMP/gateway-models-browser" --no-save --ignore-scripts playwright@1.56.1
node "$RUNNER_TEMP/gateway-models-browser/node_modules/playwright/cli.js" install --with-deps chromium
- name: Same gateway discovery oracle on candidate and disposable original base
shell: bash
run: |
set -euo pipefail
oracle=backend/internal/service/gateway_upstream_models_test.go
sha256sum "$oracle" > "$EVIDENCE_DIR/oracle.sha256"
git -C .gateway-models-baseline status --porcelain > "$EVIDENCE_DIR/baseline-before-oracle.txt"
test ! -s "$EVIDENCE_DIR/baseline-before-oracle.txt"
cp "$oracle" ".gateway-models-baseline/$oracle"
status=0
(cd .gateway-models-baseline/backend && go test -tags=unit ./internal/service -run '^TestGatewayUpstreamModelsDiscoveryAndApply$' -count=1 -v -timeout=10m) > "$EVIDENCE_DIR/discovery-red.log" 2>&1 || status=$?
printf '%s\n' "$status" > "$EVIDENCE_DIR/discovery-red-exit.txt"
cat "$EVIDENCE_DIR/discovery-red.log"
test "$status" -ne 0
grep -F 'Unsupported platform for upstream model sync: gateway' "$EVIDENCE_DIR/discovery-red.log"
if grep -Eq 'build failed|setup failed|undefined:|no tests to run|--- SKIP:|panic:|WARNING: DATA RACE' "$EVIDENCE_DIR/discovery-red.log"; then exit 1; fi
for kind in new_api sub2api; do
for action in discovery apply; do
grep -F -- "--- FAIL: TestGatewayUpstreamModelsDiscoveryAndApply/$kind/$action" "$EVIDENCE_DIR/discovery-red.log"
done
done
status=0
(cd backend && go test -tags=unit ./internal/service -run '^TestGatewayUpstreamModelsDiscoveryAndApply$' -count=1 -v -timeout=10m) > "$EVIDENCE_DIR/discovery-green.log" 2>&1 || status=$?
printf '%s\n' "$status" > "$EVIDENCE_DIR/discovery-green-exit.txt"
cat "$EVIDENCE_DIR/discovery-green.log"
test "$status" -eq 0
if grep -Eq 'no tests to run|--- SKIP:' "$EVIDENCE_DIR/discovery-green.log"; then exit 1; fi
for kind in new_api sub2api; do
for action in discovery apply; do
grep -F -- "--- PASS: TestGatewayUpstreamModelsDiscoveryAndApply/$kind/$action" "$EVIDENCE_DIR/discovery-green.log"
done
done
- name: Render complete original before and candidate applications with project CSS
id: gateway-build
if: ${{ !cancelled() }}
run: |
set -euo pipefail
ln -s "$GITHUB_WORKSPACE/frontend/node_modules" .gateway-models-baseline/frontend/node_modules
node .github/scripts/pr838-ui-build.mjs 2>&1 | tee "$EVIDENCE_DIR/build.log"
- name: Real dialog transitions with canonical synthetic API fixtures
if: ${{ !cancelled() && steps.gateway-build.outcome == 'success' }}
run: |
set -euo pipefail
status=0
node .github/scripts/gateway-models-ui.mjs > "$EVIDENCE_DIR/browser.log" 2>&1 || status=$?
printf '%s\n' "$status" > "$EVIDENCE_DIR/browser-exit.txt"
cat "$EVIDENCE_DIR/browser.log"
exit "$status"
- uses: actions/upload-artifact@v7
if: always()
with:
name: gateway-models-${{ env.CANDIDATE }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/gateway-models-evidence/*.json
${{ runner.temp }}/gateway-models-evidence/*.txt
${{ runner.temp }}/gateway-models-evidence/*.log
${{ runner.temp }}/gateway-models-evidence/*.sha256
${{ runner.temp }}/gateway-models-evidence/*.png
if-no-files-found: error
retention-days: 30
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ FRONTEND_CRITICAL_VITEST := \
src/views/admin/__tests__/AccountQualityView.spec.ts \
src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts \
src/views/admin/__tests__/AccountsView.declarationRefresh.spec.ts \
src/views/admin/__tests__/AccountsView.newAPIConfig.spec.ts \
src/utils/__tests__/accountUpstreamModelAutoSync.spec.ts \
src/utils/__tests__/qualityRulePatch.spec.ts \
src/components/admin/operations/__tests__/QualityOwnershipReview.spec.ts \
Expand Down
25 changes: 24 additions & 1 deletion backend/internal/handler/admin/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3415,14 +3415,36 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) {
Platform string `json:"platform" binding:"required"`
Type string `json:"type" binding:"required"`
BaseURL string `json:"base_url"`
APIKey string `json:"api_key" binding:"required"`
APIKey string `json:"api_key"`
AccountID *int64 `json:"account_id" binding:"omitempty,gt=0"`
ProxyID *int64 `json:"proxy_id" binding:"omitempty,gte=0"`
ModelMapping map[string]string `json:"model_mapping"`
UpstreamKind string `json:"upstream_kind"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
// Gateway edits may preview a draft URL/proxy without returning the saved
// calling key to the browser. Resolve only an accessible gateway account.
if req.AccountID != nil {
if _, observer := service.ObserverGroupIDs(c.Request.Context()); observer {
response.ErrorFrom(c, service.ErrObserverScope)
return
}
account, err := h.adminService.GetAccount(c.Request.Context(), *req.AccountID)
if err != nil || account == nil || !account.IsGateway() || req.Platform != service.PlatformGateway || req.Type != service.AccountTypeGateway {
response.BadRequest(c, "Invalid gateway preview account")
return
}
if strings.TrimSpace(req.APIKey) == "" {
req.APIKey = account.GetCredential("api_key")
}
}
if strings.TrimSpace(req.APIKey) == "" {
response.BadRequest(c, "API key is required")
return
}
modelMapping := make(map[string]any, len(req.ModelMapping))
for sourceModel, upstreamModel := range req.ModelMapping {
modelMapping[sourceModel] = upstreamModel
Expand All @@ -3432,6 +3454,7 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) {
Platform: req.Platform,
Type: req.Type,
Credentials: map[string]any{
"upstream_kind": req.UpstreamKind,
"api_key": req.APIKey,
"base_url": req.BaseURL,
"model_mapping": modelMapping,
Expand Down
100 changes: 100 additions & 0 deletions backend/internal/handler/admin/account_handler_gateway_models_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//go:build unit

package admin

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

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

type gatewayPreviewAdminService struct {
*availableModelsAdminService
}

func (s *gatewayPreviewAdminService) GetProxy(context.Context, int64) (*service.Proxy, error) {
return nil, nil
}

func TestAccountHandlerGatewayModelsDraftAndSavedConnection(t *testing.T) {
for _, kind := range []string{"new_api", "sub2api"} {
for _, draft := range []bool{false, true} {
t.Run(kind+map[bool]string{false: "/saved", true: "/draft"}[draft], func(t *testing.T) {
svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{
ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
Credentials: map[string]any{"upstream_kind": kind, "base_url": "https://saved.example/v1", "api_key": "saved-synthetic-key"},
}}
upstream := &syncUpstreamHTTPUpstream{resp: &http.Response{StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"live"}]}`))}}
router := setupSyncUpstreamModelsRouter(svc, upstream)
path, payload := "/api/v1/admin/accounts/1003/models/sync-upstream", map[string]any{}
if draft {
path = "/api/v1/admin/accounts/models/sync-upstream-preview"
payload = map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": kind,
"account_id": 1003, "base_url": "https://draft.example/tenant", "api_key": ""}
}
body, err := json.Marshal(payload)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body)))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, upstream.requests, 1)
wantURL := "https://saved.example/v1/models"
if draft {
wantURL = "https://draft.example/tenant/v1/models"
}
require.Equal(t, wantURL, upstream.requests[0].URL.String())
require.Equal(t, "Bearer saved-synthetic-key", upstream.requests[0].Header.Get("Authorization"))
require.Contains(t, rec.Body.String(), `"discovery_source":"upstream"`)
require.NotContains(t, rec.Body.String(), "saved-synthetic-key")
})
}
}
}

func TestAccountHandlerGatewayModelsPreviewRejectsObserverAndMissingProxy(t *testing.T) {
for _, scenario := range []string{"observer", "proxy", "invalid-kind", "missing-key"} {
t.Run(scenario, func(t *testing.T) {
svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{
ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://saved.example", "api_key": "synthetic-key"},
}}
payload := map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": "new_api",
"base_url": "https://draft.example", "api_key": "synthetic-key"}
want := http.StatusBadRequest
switch scenario {
case "observer":
payload["account_id"] = 1003
want = http.StatusForbidden
case "proxy":
payload["proxy_id"] = 7
case "invalid-kind":
payload["upstream_kind"] = "other"
case "missing-key":
delete(payload, "api_key")
}
upstream := &syncUpstreamHTTPUpstream{}
router := setupSyncUpstreamModelsRouter(&gatewayPreviewAdminService{availableModelsAdminService: svc}, upstream)
body, err := json.Marshal(payload)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", strings.NewReader(string(body)))
req.Header.Set("Content-Type", "application/json")
if scenario == "observer" {
req = req.WithContext(service.WithObserverScope(req.Context(), []int64{1}))
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, want, rec.Code, rec.Body.String())
require.Empty(t, upstream.requests)
})
}
}
Loading
Loading