Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

【架构优化】合并 gongfeng OAuth 中重复的 HTTP 请求与限长读取逻辑 (#241)

fx-kurumi7adeef3f066a
diff --git a/internal/gongfeng/do_test.go b/internal/gongfeng/do_test.go
new file mode 100644
index 00000000..971f0f4f
--- /dev/null
+++ b/internal/gongfeng/do_test.go
@@ -0,0 +1,43 @@
+package gongfeng
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestDoReturnsStatusAndBody(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusTeapot)
+ _, _ = w.Write([]byte("payload"))
+ }))
+ defer server.Close()
+ req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
+ status, body, err := do(req)
+ if err != nil || status != http.StatusTeapot || string(body) != "payload" {
+ t.Fatalf("do = %d, %q, %v", status, body, err)
+ }
+}
+
+func TestDoLimitsResponseBody(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(strings.Repeat("x", maxResponseBytes+1024)))
+ }))
+ defer server.Close()
+ req, _ := http.NewRequest(http.MethodGet, server.URL, nil)
+ status, body, err := do(req)
+ if err != nil || status != http.StatusOK || len(body) != maxResponseBytes {
+ t.Fatalf("do = %d, len %d, %v", status, len(body), err)
+ }
+}
+
+func TestDoWrapsConnectionError(t *testing.T) {
+ server := httptest.NewServer(http.NotFoundHandler())
+ url := server.URL
+ server.Close()
+ req, _ := http.NewRequest(http.MethodGet, url, nil)
+ if _, _, err := do(req); err == nil || !strings.HasPrefix(err.Error(), "无法连接工蜂:") {
+ t.Fatalf("do error = %v", err)
+ }
+}
diff --git a/internal/gongfeng/oauth.go b/internal/gongfeng/oauth.go
index 69a0b749..02780758 100644
--- a/internal/gongfeng/oauth.go
+++ b/internal/gongfeng/oauth.go
@@ -22,6 +22,8 @@ const (
// Repository clone and push need both scopes. The application must allow them.
RepositoryScope = "read_repository write_repository"
defaultTTL = 2 * time.Hour
+ // maxResponseBytes caps how much of any Gongfeng response body is read.
+ maxResponseBytes = 64 << 10
)
// httpClient bounds every call to the Gongfeng OAuth endpoints. A refresh runs
@@ -137,17 +139,12 @@ func Username(ctx context.Context, cfg Config, accessToken string) (string, erro
return "", err
}
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(accessToken))
- resp, err := httpClient.Do(req)
- if err != nil {
- return "", fmt.Errorf("无法连接工蜂:%v", err)
- }
- defer resp.Body.Close()
- body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ status, body, err := do(req)
if err != nil {
return "", err
}
- if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("工蜂用户信息返回 HTTP %d", resp.StatusCode)
+ if status != http.StatusOK {
+ return "", fmt.Errorf("工蜂用户信息返回 HTTP %d", status)
}
var user struct {
Username string `json:"username"`
@@ -168,17 +165,12 @@ func requestToken(ctx context.Context, cfg Config, form url.Values) (Token, erro
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
- resp, err := httpClient.Do(req)
- if err != nil {
- return Token{}, fmt.Errorf("无法连接工蜂:%v", err)
- }
- defer resp.Body.Close()
- body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ status, body, err := do(req)
if err != nil {
return Token{}, err
}
- if resp.StatusCode != http.StatusOK {
- return Token{}, fmt.Errorf("工蜂令牌接口返回 HTTP %d:%s", resp.StatusCode, redact(cfg, truncate(string(body), 180)))
+ if status != http.StatusOK {
+ return Token{}, fmt.Errorf("工蜂令牌接口返回 HTTP %d:%s", status, redact(cfg, truncate(string(body), 180)))
}
var raw struct {
AccessToken string `json:"access_token"`
@@ -203,6 +195,22 @@ func requestToken(ctx context.Context, cfg Config, form url.Values) (Token, erro
return Token{AccessToken: raw.AccessToken, RefreshToken: raw.RefreshToken, ExpiresIn: raw.ExpiresIn}, nil
}
+// do sends req with the bounded client and returns the status code and at
+// most maxResponseBytes of the body. Transport failures are reported as a
+// connection error so callers only handle status and payload.
+func do(req *http.Request) (int, []byte, error) {
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return 0, nil, fmt.Errorf("无法连接工蜂:%v", err)
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
+ if err != nil {
+ return 0, nil, err
+ }
+ return resp.StatusCode, body, nil
+}
+
func redact(cfg Config, msg string) string {
if cfg.ClientSecret != "" {
msg = strings.ReplaceAll(msg, cfg.ClientSecret, "***")
diff --git a/internal/gongfeng/oauth_do_callers_test.go b/internal/gongfeng/oauth_do_callers_test.go
new file mode 100644
index 00000000..07548464
--- /dev/null
+++ b/internal/gongfeng/oauth_do_callers_test.go
@@ -0,0 +1,78 @@
+package gongfeng
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// Username and requestToken both route through do; a transport failure must
+// surface as the shared connection error instead of a status/parse error.
+func TestOAuthCallersPropagateConnectionError(t *testing.T) {
+ server := httptest.NewServer(http.NotFoundHandler())
+ base := server.URL
+ server.Close()
+ cfg := Config{ClientID: "id", ClientSecret: "secret", RedirectURI: "https://app/cb", AuthorizeURL: base + "/authorize", TokenURL: base + "/token", APIBase: base + "/api"}
+ if _, err := Username(context.Background(), cfg, "access"); err == nil || !strings.HasPrefix(err.Error(), "无法连接工蜂:") {
+ t.Fatalf("username error = %v", err)
+ }
+ if _, err := Exchange(context.Background(), cfg, "code"); err == nil || !strings.HasPrefix(err.Error(), "无法连接工蜂:") {
+ t.Fatalf("exchange error = %v", err)
+ }
+ if _, err := Refresh(context.Background(), cfg, "refresh"); err == nil || !strings.HasPrefix(err.Error(), "无法连接工蜂:") {
+ t.Fatalf("refresh error = %v", err)
+ }
+}
+
+func TestOAuthCallersRejectUnusablePayloads(t *testing.T) {
+ big := strings.Repeat("y", maxResponseBytes+4096)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api-blank/user":
+ _, _ = w.Write([]byte(`{"username":" "}`))
+ case "/api-badjson/user":
+ _, _ = w.Write([]byte("{"))
+ case "/api-huge/user":
+ // A valid object followed by more than the cap: the truncated body
+ // must not parse, proving Username consumes the bounded read.
+ _, _ = w.Write([]byte(`{"username":"` + big + `"}`))
+ case "/token":
+ _ = r.ParseForm()
+ switch r.Form.Get("code") {
+ case "empty":
+ _, _ = w.Write([]byte(`{}`))
+ case "described":
+ _, _ = w.Write([]byte(`{"error":"denied","error_description":"bad secret for id"}`))
+ case "huge-error":
+ w.WriteHeader(http.StatusBadGateway)
+ _, _ = w.Write([]byte(big))
+ }
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+ cfg := Config{ClientID: "id", ClientSecret: "secret", RedirectURI: "https://app/cb", AuthorizeURL: server.URL + "/authorize", TokenURL: server.URL + "/token"}
+
+ for _, api := range []string{"/api-blank", "/api-badjson", "/api-huge"} {
+ c := cfg
+ c.APIBase = server.URL + api
+ if _, err := Username(context.Background(), c, "access"); err == nil || err.Error() != "工蜂用户信息无法解析" {
+ t.Fatalf("%s username error = %v", api, err)
+ }
+ }
+
+ if _, err := Exchange(context.Background(), cfg, "empty"); err == nil || !strings.Contains(err.Error(), "响应里没有 access_token") {
+ t.Fatalf("empty token error = %v", err)
+ }
+ _, err := Exchange(context.Background(), cfg, "described")
+ if err == nil || !strings.Contains(err.Error(), "bad *** for id") || strings.Contains(err.Error(), "denied") {
+ t.Fatalf("described token error = %v", err)
+ }
+ _, err = Exchange(context.Background(), cfg, "huge-error")
+ if err == nil || !strings.HasPrefix(err.Error(), "工蜂令牌接口返回 HTTP 502:") || len(err.Error()) > 512 {
+ t.Fatalf("huge error = %.80v", err)
+ }
+}