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
78 changes: 78 additions & 0 deletions .github/scripts/bps-auth-preview.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// CI-only component rendering; all API responses and callback values are synthetic.
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'

const [repoArg, outputArg] = process.argv.slice(2)
const repo = resolve(repoArg), output = resolve(outputArg), root = join(repo, 'frontend')
const require = createRequire(join(root, 'package.json'))
const { createServer } = await import(pathToFileURL(join(dirname(require.resolve('vite/package.json')), 'dist/node/index.js')).href)
const vue = (await import(pathToFileURL(require.resolve('@vitejs/plugin-vue')).href)).default
const { chromium } = await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE).href)
const entry = '.bps-auth-preview.js', cacheDir = mkdtempSync(join(tmpdir(), 'bps-auth-preview-'))
const baseline = '0b9cbfbabb2d0ff03adc7f3f5f65b9b4edaa029b'
let before = true, server, browser
mkdirSync(output, { recursive: true })
try {
writeFileSync(join(root, entry), `
import {mount} from '@vue/test-utils';
import {createPinia} from 'pinia';
import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
import {apiClient} from '/src/api/client.ts';
import View from '/src/components/account/OpenAIAuthConnections.vue';
import '/src/style.css';
await loadLocaleMessages('zh'); i18n.global.locale.value='zh';
window.statusResult='unconfirmed'; window.callbackCalls=0;
const connection={id:'fixture',account_id:42,kind:'bps',label:'示例 BPS 连接',legacy:false,status:'active',client_id:'fixture-client',identity_verified:true,scopes:[],capabilities:['responses'],preferred:true,revision:2};
apiClient.defaults.adapter=async config=>{
let data;
if(config.url.endsWith('/callback')){window.callbackCalls++;throw Error('Synthetic lost response')}
else if(config.url.endsWith('/authorize'))data={session_id:'1234567890abcdef1234567890abcdef',auth_url:'https://auth.example.invalid/authorize'};
else if(config.url.endsWith('/authorization-status'))data={status:window.statusResult};
else if(config.method==='get')data=[connection];
else throw Error('Unexpected fixture request');
return {config,status:200,statusText:'OK',headers:{},data:{code:0,data}};
};
document.querySelector('#app').innerHTML='<p class="mb-4 text-gray-500">账号编辑 → 授权连接 · 实际 Vue 组件 / 虚构数据</p><div id="preview"></div>';
window.preview=mount(View,{attachTo:'#preview',props:{accountId:42,accountType:'oauth',active:true},global:{plugins:[createPinia(),i18n]}});
`)
process.chdir(root)
server = await createServer({ root, configFile: false, cacheDir,
resolve: { alias: { '@': join(root, 'src') } },
plugins: [{ name: 'bps-auth-fixture', enforce: 'pre', load(id) {
if (before && id === join(root, 'src/components/account/OpenAIAuthConnections.vue')) return execFileSync('git', ['show', baseline + ':frontend/src/components/account/OpenAIAuthConnections.vue'], { cwd: repo, encoding: 'utf8' })
}, configureServer(vite) { vite.middlewares.use((request, response, next) => {
if (request.url === '/') { response.setHeader('Content-Type','text/html'); response.end('<!doctype html><html lang="zh"><meta charset="utf-8"><div id="app" style="padding:24px;max-width:920px;margin:auto"></div><script type="module" src="/' + entry + '"></script></html>') }
else if (request.url === '/favicon.ico') { response.statusCode = 204; response.end() }
else next()
}) } }, vue()], server: { host: '127.0.0.1', port: 4298, strictPort: true },
optimizeDeps: { entries: [], include: ['vue', 'pinia', 'vue-i18n', 'axios', '@vue/test-utils'] } })
await server.listen(); browser = await chromium.launch({ headless: true })
const page = await browser.newPage({ viewport: { width: 1100, height: 980 } })
const errors = []
page.on('pageerror', e => errors.push(e.message))
await page.route('**/*', route => new URL(route.request().url()).origin === 'http://127.0.0.1:4298' ? route.continue() : route.abort())
const begin = async () => { await page.getByRole('button', { name: '授权 / 重新登录', exact: true }).click(); await page.locator('#connection-callback-42').waitFor() }
await page.goto('http://127.0.0.1:4298', { waitUntil: 'networkidle' }); await begin()
await page.screenshot({ path: join(output, 'before.png'), fullPage: true })
before = false; server.moduleGraph.invalidateAll()
await page.reload({ waitUntil: 'networkidle' }); await begin()
await page.locator('#connection-callback-42').fill('https://example.invalid/callback?code=fixture&state=fixture')
await page.getByRole('button', { name: '完成授权', exact: true }).click()
await page.getByTestId('authorization-result').waitFor()
await page.waitForFunction(() => !document.querySelector('[data-testid="check-authorization"]').disabled)
await page.screenshot({ path: join(output, 'unconfirmed.png'), fullPage: true })
await page.evaluate(() => { window.statusResult = 'saved' })
await page.getByTestId('check-authorization').click()
await page.getByText('授权凭据已保存。模型是否可用请另行查看模型列表。', { exact: true }).waitFor()
await page.screenshot({ path: join(output, 'saved.png'), fullPage: true })
const calls = await page.evaluate(() => window.callbackCalls)
if (calls !== 1 || errors.length) throw Error(JSON.stringify({calls,errors}))
writeFileSync(join(output, 'evidence.json'), JSON.stringify({ source: execFileSync('git',['rev-parse','HEAD'],{cwd:repo,encoding:'utf8'}).trim(), baseline, callback_calls: calls, errors, fixture: true }, null, 2))
} finally {
await browser?.close(); await server?.close()
rmSync(join(root, entry), { force: true }); rmSync(cacheDir, { recursive: true, force: true })
}
5 changes: 3 additions & 2 deletions .github/scripts/ci-ubuntu-mirrors.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#!/usr/bin/env bash
# Ubuntu's authoritative DNS outage can block both Azure and primary mirrors.
# Use MIT's HTTPS Ubuntu mirror in disposable CI; apt retains Ubuntu's signed
# Keep MIT and Ubuntu HTTPS mirrors so a single mirror outage cannot block CI.
# apt retains Ubuntu's signed
# Release/package verification. Never apply this helper to a production host.
set -euo pipefail
[[ "${GITHUB_ACTIONS:-}" == "true" ]] || { echo "CI-only helper" >&2; exit 1; }
for mirror_list in /etc/apt/apt-mirrors.txt /etc/apt/apt-security-mirrors.txt; do
if [[ -f "$mirror_list" ]]; then
printf '%s\n' 'https://mirrors.mit.edu/ubuntu' | sudo tee "$mirror_list" >/dev/null
printf '%s\n' 'https://mirrors.mit.edu/ubuntu' 'https://archive.ubuntu.com/ubuntu' | sudo tee "$mirror_list" >/dev/null
fi
done
67 changes: 67 additions & 0 deletions .github/workflows/bps-diagnostics-auth.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
name: BPS diagnostics and authorization

on:
pull_request:
paths:
- backend/internal/service/basispoints/**
- backend/internal/service/openai_auth_connection*
- backend/internal/handler/admin/openai_auth_connections*
- frontend/src/components/account/OpenAIAuthConnections.vue
- frontend/src/components/account/__tests__/OpenAIAuthConnections.spec.ts
- frontend/src/api/admin/openaiAuthConnections.ts
- .github/scripts/bps-auth-preview.mjs
- .github/workflows/bps-diagnostics-auth.yml
workflow_dispatch:

permissions:
contents: read

jobs:
protocol-and-receipt:
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
- working-directory: backend
run: go test -race ./internal/service/basispoints -count=1 -v
- working-directory: backend
run: go test -race -tags=unit ./internal/service ./internal/handler/admin ./internal/server/middleware -run 'Test(ExcelBPSToolArgumentsDiagnostic|ConnectionAuthorizationStatus|OpenAIConnectionManagement|OpenAIConnectionHandlerAccountType|OpenAIAuthConnection|Audit)' -count=1 -v -timeout=10m
authorization-ui:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
- 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
- run: pnpm --dir frontend install --frozen-lockfile
- run: pnpm --dir frontend exec vitest run src/components/account/__tests__/OpenAIAuthConnections.spec.ts src/i18n/__tests__/localeKeyCompleteness.spec.ts
- run: pnpm --dir frontend typecheck
- name: Install isolated screenshot browser
run: |
npm install --prefix "$RUNNER_TEMP/bps-browser" --no-save --ignore-scripts playwright@1.56.1
node "$RUNNER_TEMP/bps-browser/node_modules/playwright/cli.js" install --with-deps chromium
- name: Render actual authorization component with synthetic callbacks
env:
SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/bps-browser/node_modules/playwright/index.mjs
run: node .github/scripts/bps-auth-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/bps-auth-evidence"
- uses: actions/upload-artifact@v7
if: always()
with:
name: bps-auth-evidence-${{ github.event.pull_request.head.sha || github.sha }}
path: ${{ runner.temp }}/bps-auth-evidence
retention-days: 30
12 changes: 12 additions & 0 deletions .github/workflows/openai-connection-account-type-regression.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ jobs:
backend/internal/service/openai_auth_connection_oauth.go \
backend/internal/service/openai_auth_connection_legacy.go \
backend/internal/service/openai_auth_connection_routing.go
# The new status endpoint compiles with a management helper absent
# from this old baseline. Retain that exact helper only: the restored
# List/Create methods still run their historical account-type logic.
python3 - <<'PYCODE'
import pathlib, re, subprocess
source = subprocess.check_output(['git', 'show', 'HEAD:backend/internal/service/openai_auth_connections.go'], text=True)
helper = re.search(r'func \(s \*OpenAIOAuthReauthService\) managementConnectionAccount\(.*?\n\}', source, re.S)
assert helper is not None
target = pathlib.Path('backend/internal/service/connection_type_red_compat.go')
assert not target.exists()
target.write_text('package service\nimport ("context"; infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors")\n' + helper.group(0) + '\n')
PYCODE
fi
git rev-parse HEAD | tee "$RUNNER_TEMP/connection-proof/head.txt"
git diff --name-only | tee "$RUNNER_TEMP/connection-proof/restored-paths.txt"
Expand Down
23 changes: 23 additions & 0 deletions backend/internal/handler/admin/openai_auth_connections.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,29 @@ func (h *OpenAIOAuthReauthHandler) CompleteConnectionAuthorization(c *gin.Contex
}
response.Success(c, gin.H{"authorized": true})
}

// Use a body rather than URL parameters so session identifiers are not copied
// to ordinary access logs, browser history or referrers.
func (h *OpenAIOAuthReauthHandler) ConnectionAuthorizationStatus(c *gin.Context) {
c.Header("Cache-Control", "no-store")
id, ok := parseReauthAccountID(c)
if !ok {
return
}
var input struct {
SessionID string `json:"session_id" binding:"required"`
}
if c.ShouldBindJSON(&input) != nil {
response.BadRequest(c, "Session is required")
return
}
result, err := h.service.ConnectionAuthorizationStatus(c.Request.Context(), id, c.Param("connection_id"), input.SessionID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
func (h *OpenAIOAuthReauthHandler) RevokeAuthConnection(c *gin.Context) {
id, ok := parseReauthAccountID(c)
if !ok {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func TestOpenAIConnectionHandlerAccountType(t *testing.T) {
router.PATCH(prefix+"/:connection_id", h.UpdateAuthConnection)
router.POST(prefix+"/:connection_id/authorize", h.BeginConnectionAuthorization)
router.POST(prefix+"/:connection_id/callback", h.CompleteConnectionAuthorization)
router.POST(prefix+"/:connection_id/authorization-status", h.ConnectionAuthorizationStatus)
router.POST(prefix+"/:connection_id/revoke", h.RevokeAuthConnection)
router.PUT(prefix+"/:connection_id/api-key", h.RotateConnectionAPIKey)
cases := []struct{ name, method, suffix, body string }{
Expand All @@ -66,6 +67,7 @@ func TestOpenAIConnectionHandlerAccountType(t *testing.T) {
cases = append(cases, []struct{ name, method, suffix, body string }{
{"authorize", "POST", "/" + id + "/authorize", ""},
{"callback", "POST", "/" + id + "/callback", `{"session_id":"synthetic","callback_url":"https://example.invalid"}`},
{"authorization_status", "POST", "/" + id + "/authorization-status", `{"session_id":"1234567890abcdef1234567890abcdef"}`},
{"revoke", "POST", "/" + id + "/revoke", `{"revision":1}`},
{"rotate", "PUT", "/" + id + "/api-key", `{"revision":1,"api_key":"synthetic"}`},
{"legacy", "POST", "/use-legacy", ""},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package middleware

import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"

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

func TestAuditConnectionAuthorizationOmitsSessionAndCallback(t *testing.T) {
for _, action := range []string{"callback", "authorization-status"} {
t.Run(action, func(t *testing.T) {
repository := &auditCaptureRepository{}
auditService := service.NewAuditLogService(repository, nil)
auditService.Start()
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(ContextKeyUser), AuthSubject{UserID: 17})
c.Set(string(ContextKeyUserRole), "admin")
c.Next()
})
router.Use(gin.HandlerFunc(NewAuditLogMiddleware(auditService)))
body := `{"session_id":"PRIVATE_SESSION","callback_url":"https://example.invalid/?code=PRIVATE_CODE&state=PRIVATE_STATE"}`
router.POST("/api/v1/admin/accounts/:id/auth-connections/:connection_id/"+action, func(c *gin.Context) {
got, err := io.ReadAll(c.Request.Body)
require.NoError(t, err)
require.Equal(t, body, string(got))
c.Status(http.StatusOK)
})
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/auth-connections/fixture/"+action, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
auditService.Stop()
require.Equal(t, http.StatusOK, rec.Code)
require.Len(t, repository.logs, 1)
require.Equal(t, "<credential-bearing body omitted>", repository.logs[0].RequestBody)
})
}
}
44 changes: 23 additions & 21 deletions backend/internal/server/middleware/audit_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,27 +173,29 @@ var auditActionOverrides = map[string]string{
// auditBodyOmittedRoutes 请求体几乎整体由凭证构成的路由(如整块粘贴 auth JSON 的导入接口)。
// 这类 body 的凭证内嵌在普通字符串值里,键级脱敏无法覆盖,整体不入库。
var auditBodyOmittedRoutes = map[string]struct{}{
"POST /api/v1/admin/upstream-channels": {},
"PUT /api/v1/admin/upstream-channels/:id": {},
"DELETE /api/v1/admin/upstream-channels/:id": {},
"PUT /api/v1/admin/upstream-channel-bindings": {},
"POST /api/v1/admin/settings/ip-audit/release": {},
"PUT /api/v1/admin/settings/ip-risk": {},
"POST /api/v1/admin/settings/ip-risk/anonymous-unban": {},
"POST /api/v1/admin/accounts/:id/export-session": {},
"PUT /api/v1/admin/account-ops/webhooks/:id": {},
"PUT /api/v1/admin/account-ops/config": {},
"POST /api/v1/admin/account-ops/token-guard/two-fa-login": {},
"POST /api/v1/auth/passkey/login/finish": {},
"POST /api/v1/user/passkeys/register/finish": {},
"POST /api/v1/admin/accounts/import/codex-session": {},
"PUT /api/v1/admin/accounts/:id/ollama-cloud-usage/session": {},
"PUT /api/v1/admin/prompt-audit/config": {},
"POST /api/v1/admin/prompt-audit/endpoints/probe": {},
"DELETE /api/v1/admin/prompt-audit/events/:id": {},
"POST /api/v1/admin/prompt-audit/events/batch-delete": {},
"POST /api/v1/admin/prompt-audit/events/delete-preview": {},
"POST /api/v1/admin/prompt-audit/events/delete-by-filter": {},
"POST /api/v1/admin/accounts/:id/auth-connections/:connection_id/authorization-status": {},
"POST /api/v1/admin/accounts/:id/auth-connections/:connection_id/callback": {},
"POST /api/v1/admin/upstream-channels": {},
"PUT /api/v1/admin/upstream-channels/:id": {},
"DELETE /api/v1/admin/upstream-channels/:id": {},
"PUT /api/v1/admin/upstream-channel-bindings": {},
"POST /api/v1/admin/settings/ip-audit/release": {},
"PUT /api/v1/admin/settings/ip-risk": {},
"POST /api/v1/admin/settings/ip-risk/anonymous-unban": {},
"POST /api/v1/admin/accounts/:id/export-session": {},
"PUT /api/v1/admin/account-ops/webhooks/:id": {},
"PUT /api/v1/admin/account-ops/config": {},
"POST /api/v1/admin/account-ops/token-guard/two-fa-login": {},
"POST /api/v1/auth/passkey/login/finish": {},
"POST /api/v1/user/passkeys/register/finish": {},
"POST /api/v1/admin/accounts/import/codex-session": {},
"PUT /api/v1/admin/accounts/:id/ollama-cloud-usage/session": {},
"PUT /api/v1/admin/prompt-audit/config": {},
"POST /api/v1/admin/prompt-audit/endpoints/probe": {},
"DELETE /api/v1/admin/prompt-audit/events/:id": {},
"POST /api/v1/admin/prompt-audit/events/batch-delete": {},
"POST /api/v1/admin/prompt-audit/events/delete-preview": {},
"POST /api/v1/admin/prompt-audit/events/delete-by-filter": {},
}

// NewAuditLogMiddleware 创建审计中间件。
Expand Down
1 change: 1 addition & 0 deletions backend/internal/server/routes/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpAu
accounts.PATCH("/:id/auth-connections/:connection_id", h.Admin.OpenAIOAuthReauth.UpdateAuthConnection)
accounts.POST("/:id/auth-connections/:connection_id/authorize", h.Admin.OpenAIOAuthReauth.BeginConnectionAuthorization)
accounts.POST("/:id/auth-connections/:connection_id/callback", h.Admin.OpenAIOAuthReauth.CompleteConnectionAuthorization)
accounts.POST("/:id/auth-connections/:connection_id/authorization-status", h.Admin.OpenAIOAuthReauth.ConnectionAuthorizationStatus)
accounts.POST("/:id/auth-connections/:connection_id/revoke", h.Admin.OpenAIOAuthReauth.RevokeAuthConnection)
accounts.GET("/:id/openai-reauth", h.Admin.OpenAIOAuthReauth.GetStatus)
accounts.GET("/:id/siwc", h.Admin.OpenAIOAuthReauth.SIWCStatus)
Expand Down
Loading
Loading