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
122 changes: 74 additions & 48 deletions internal/app/admin.go

Large diffs are not rendered by default.

137 changes: 137 additions & 0 deletions internal/app/admin_i18n_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package app

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
)

// adminRequestIn mirrors adminRequest but sets Accept-Language, which is what
// the WebUI sends to have the admin API answer in the selected UI language.
func adminRequestIn(t *testing.T, srv *httptest.Server, method, path, password, lang string, body any) (*http.Response, map[string]any) {
t.Helper()
var reader *bytes.Reader
if body != nil {
data, _ := json.Marshal(body)
reader = bytes.NewReader(data)
} else {
reader = bytes.NewReader(nil)
}
req, err := http.NewRequest(method, srv.URL+path, reader)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+password)
if lang != "" {
req.Header.Set("Accept-Language", lang)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var payload map[string]any
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
t.Fatalf("decode %s %s: %v", method, path, err)
}
return resp, payload
}

func errorOf(t *testing.T, payload map[string]any) string {
t.Helper()
msg, _ := payload["error"].(string)
if msg == "" {
t.Fatalf("payload has no error message: %#v", payload)
}
return msg
}

// TestAdminErrorsFollowAcceptLanguage covers the three ways a message reaches
// the client: messages composed in the handler, messages produced by a deeper
// layer, and errors that wrap an underlying cause.
func TestAdminErrorsFollowAcceptLanguage(t *testing.T) {
srv, _, _, _, _, _ := newAdminTestEnv(t)

t.Run("handler message, chinese", func(t *testing.T) {
resp, payload := adminRequestIn(t, srv, "PATCH", "/admin/api/accounts/missing", "admin-pass-123", "zh-CN,zh;q=0.9,en;q=0.8", map[string]any{"enabled": false})
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404", resp.StatusCode)
}
if got := errorOf(t, payload); got != "账号不存在" {
t.Errorf("error = %q, want %q", got, "账号不存在")
}
})

t.Run("handler message, english default", func(t *testing.T) {
resp, payload := adminRequestIn(t, srv, "PATCH", "/admin/api/accounts/missing", "admin-pass-123", "de-DE,de;q=0.9", map[string]any{"enabled": false})
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404", resp.StatusCode)
}
if got := errorOf(t, payload); got != "account not found" {
t.Errorf("error = %q, want %q", got, "account not found")
}
})

t.Run("domain layer message", func(t *testing.T) {
resp, payload := adminRequestIn(t, srv, "POST", "/admin/api/accounts", "admin-pass-123", "zh-CN", map[string]any{"name": "empty-key"})
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409", resp.StatusCode)
}
if got := errorOf(t, payload); got != "api_key 不能为空" {
t.Errorf("error = %q, want %q", got, "api_key 不能为空")
}
})

t.Run("wrapped cause keeps its detail", func(t *testing.T) {
// Point persistence into a directory that does not exist, so saving
// fails and the handler wraps the filesystem error.
configFile = filepath.Join(t.TempDir(), "missing-dir", "config.yaml")
resp, payload := adminRequestIn(t, srv, "PUT", "/admin/api/settings", "admin-pass-123", "zh-CN", map[string]any{"base_url": "https://api.example.test"})
if resp.StatusCode != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", resp.StatusCode)
}
got := errorOf(t, payload)
if !strings.HasPrefix(got, "已应用,但保存配置失败:") {
t.Errorf("error = %q, want the localized wrapper prefix", got)
}
if !strings.Contains(got, "missing-dir") {
t.Errorf("error = %q, want the underlying cause kept verbatim", got)
}
})
}

// TestAdminAuthErrorsFollowAcceptLanguage localizes the middleware, which
// answers before any handler runs, including the lockout message.
func TestAdminAuthErrorsFollowAcceptLanguage(t *testing.T) {
srv, _, _, _, _, _ := newAdminTestEnv(t)

resp, payload := adminRequestIn(t, srv, "GET", "/admin/api/overview", "wrong", "zh-CN", nil)
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", resp.StatusCode)
}
if got := errorOf(t, payload); got != "管理密码不正确" {
t.Errorf("error = %q, want %q", got, "管理密码不正确")
}

// Repeated failures arm the lockout; the lockout message is localized too.
locked := false
for i := 0; i < adminFailLimit+1 && !locked; i++ {
attempt, _ := adminRequestIn(t, srv, "GET", "/admin/api/overview", "wrong", "zh-CN", nil)
locked = attempt.StatusCode == http.StatusTooManyRequests
}
if !locked {
t.Fatal("admin auth never locked out after repeated failures")
}
resp, payload = adminRequestIn(t, srv, "GET", "/admin/api/overview", "admin-pass-123", "zh-CN", nil)
if resp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("status = %d, want 429", resp.StatusCode)
}
got := errorOf(t, payload)
if !strings.HasPrefix(got, "失败次数过多,请 ") || !strings.HasSuffix(got, " 秒后重试") {
t.Errorf("error = %q, want the localized lockout message", got)
}
}
38 changes: 38 additions & 0 deletions internal/app/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"testing"

"cmdcode2api/internal/i18n"
)

// newAdminTestEnv starts an admin API server backed by temp-dir persistence.
Expand Down Expand Up @@ -400,3 +402,39 @@ func TestConfigFileRedirectedForAdminPersistence(t *testing.T) {
t.Fatalf("config file not written: %v", err)
}
}

func TestLocalizeQuotaSnapshot(t *testing.T) {
snap := &QuotaSnapshot{
LastError: "API key rejected: HTTP 401",
Failures: []string{"whoami: context deadline exceeded", "quota endpoints returned no data"},
}

// English (the source of truth) returns the snapshot unchanged.
if got := localizeQuotaSnapshot(i18n.EN, snap); got != snap {
t.Fatalf("EN should return the same snapshot, got %+v", got)
}

// Chinese translates both fields and leaves the stored snapshot intact.
got := localizeQuotaSnapshot(i18n.ZHCN, snap)
if got.LastError != "API Key 被拒绝:HTTP 401" {
t.Fatalf("LastError = %q", got.LastError)
}
wantFailures := []string{"whoami: context deadline exceeded", "额度接口返回空数据"}
if len(got.Failures) != len(wantFailures) || got.Failures[0] != wantFailures[0] || got.Failures[1] != wantFailures[1] {
t.Fatalf("Failures = %v, want %v", got.Failures, wantFailures)
}
if snap.LastError != "API key rejected: HTTP 401" || len(snap.Failures) != 2 {
t.Fatalf("stored snapshot was mutated: %+v", snap)
}

// A snapshot without error texts is passed through untouched.
clean := &QuotaSnapshot{MonthlyCredits: floatPtr(1)}
if got := localizeQuotaSnapshot(i18n.ZHCN, clean); got != clean {
t.Fatalf("clean snapshot should be returned as-is, got %+v", got)
}

// Nil is nil-safe (mirrors usage.Quota returning nil for unknown accounts).
if got := localizeQuotaSnapshot(i18n.ZHCN, nil); got != nil {
t.Fatalf("nil snapshot = %+v, want nil", got)
}
}
10 changes: 5 additions & 5 deletions internal/app/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) {
}
}
if err != nil {
return nil, fmt.Errorf("无法启动回调服务器: %w", err)
return nil, fmt.Errorf("start callback server: %w", err)
}
}

Expand Down Expand Up @@ -142,7 +142,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(map[string]any{"success": true})
errCh <- fmt.Errorf("授权被取消: %s", errMsg[0])
errCh <- fmt.Errorf("authorization canceled: %s", errMsg[0])
return
}

Expand All @@ -151,7 +151,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) {
w.WriteHeader(400)
json.NewEncoder(w).Encode(map[string]any{
"success": false,
"error": "缺少必要字段",
"error": "api_key and state are required",
})
return
}
Expand Down Expand Up @@ -239,7 +239,7 @@ func (f *OAuthFlow) deliver(cb oauthCallback) error {
default:
}
if cb.State != f.State {
return fmt.Errorf("state token 不匹配,可能被篡改")
return fmt.Errorf("state token mismatch (possible tampering)")
}
f.mu.Lock()
f.result = &cb
Expand All @@ -259,7 +259,7 @@ func (f *OAuthFlow) Wait(timeout time.Duration) (oauthCallback, error) {
select {
case cb := <-f.resultCh:
if cb.State != f.State {
err := fmt.Errorf("state token 不匹配,可能被篡改")
err := fmt.Errorf("state token mismatch (possible tampering)")
f.finish(err)
return oauthCallback{}, err
}
Expand Down
6 changes: 3 additions & 3 deletions internal/app/quota.go
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe
orgID := ""
if who, err := quotaGet(ctx, client, base+"/alpha/whoami", apiKey); err != nil {
if quotaKeyRejected(err) {
return nil, fmt.Errorf("API Key 被拒绝(%v)", err)
return nil, fmt.Errorf("API key rejected: %v", err)
}
failures = append(failures, "whoami: "+err.Error())
} else {
Expand Down Expand Up @@ -488,9 +488,9 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe
}
if !snapshotHasData(snap) {
if len(failures) == 0 {
return nil, fmt.Errorf("额度接口返回空数据")
return nil, fmt.Errorf("quota endpoints returned no data")
}
return nil, fmt.Errorf("所有额度接口均无法访问:%s", strings.Join(failures, "; "))
return nil, fmt.Errorf("all quota endpoints failed: %s", strings.Join(failures, "; "))
}
return snap, nil
}
Expand Down
2 changes: 1 addition & 1 deletion internal/app/quota_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ func TestFetchQuotaSnapshotNonJSONFailsWhenNoData(t *testing.T) {
defer srv.Close()

_, err := fetchQuotaSnapshot(context.Background(), srv.Client(), srv.URL, "cc-key")
if err == nil || !strings.Contains(err.Error(), "所有额度接口均无法访问") {
if err == nil || !strings.Contains(err.Error(), "all quota endpoints failed") {
t.Fatalf("err = %v, want aggregate failure", err)
}
}
Expand Down
9 changes: 5 additions & 4 deletions internal/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"syscall"
"time"

"cmdcode2api/internal/i18n"
"cmdcode2api/internal/web"
)

Expand Down Expand Up @@ -95,20 +96,20 @@ func adminAuth(cfg *Config, limiter *ipRateLimiter) func(http.Handler) http.Hand
if ok, retryAfter := limiter.Allow(ip); !ok {
seconds := int(retryAfter.Seconds()) + 1
w.Header().Set("Retry-After", strconv.Itoa(seconds))
writeAdminError(w, http.StatusTooManyRequests,
fmt.Sprintf("失败次数过多,请 %d 秒后重试", seconds))
writeAdminError(w, r, http.StatusTooManyRequests,
i18n.Message(i18n.FromRequest(r), "too many failed attempts, retry in %d seconds", seconds))
return
}
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
limiter.Fail(ip)
writeAdminError(w, 401, "missing Authorization header")
writeAdminError(w, r, 401, "missing Authorization header")
return
}
key := strings.TrimPrefix(auth, "Bearer ")
if !subtleConstantTimeEqual(key, cfg.adminPassword()) {
limiter.Fail(ip)
writeAdminError(w, 401, "invalid admin password")
writeAdminError(w, r, 401, "invalid admin password")
return
}
limiter.Reset(ip)
Expand Down
Loading