From 6d1fbbd7ef1ce31343d16d16a18b41c6cfd5dd0f Mon Sep 17 00:00:00 2001 From: MurphyYi Date: Fri, 13 Nov 2026 01:14:14 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E6=B8=85=E9=9B=B6=E8=BD=A6=E9=81=93?= =?UTF-8?q?=20Y4=20=E4=B8=89=E5=8D=95(#12-#14)=E2=80=94=E2=80=94404=20?= =?UTF-8?q?=E5=88=A4=E5=AE=9A=E6=94=B9=20errors.As=20=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E5=8C=96=E5=88=86=E6=B5=81/FindActionRunByHeadSHA=20=E8=A7=A6?= =?UTF-8?q?=E9=A1=B6=20yield=20ErrTooManyPages=20=E4=B8=8E=20Paginate=20?= =?UTF-8?q?=E5=90=8C=E7=BA=AA=E5=BE=8B/RetryPolicy.Multiplier=20=E9=9B=B6?= =?UTF-8?q?=E5=80=BC=E6=8C=89=E6=96=87=E6=A1=A3=E7=BC=BA=E7=9C=81=202.0=20?= =?UTF-8?q?=E5=BD=92=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- actions_v8.go | 20 +++- client.go | 28 ++--- client_enhanced_test.go | 3 +- hardening_y4_test.go | 249 ++++++++++++++++++++++++++++++++++++++++ pulls.go | 3 +- retry.go | 16 ++- types.go | 2 +- 7 files changed, 292 insertions(+), 29 deletions(-) create mode 100644 hardening_y4_test.go diff --git a/actions_v8.go b/actions_v8.go index 94e6918..f7a4139 100644 --- a/actions_v8.go +++ b/actions_v8.go @@ -25,6 +25,7 @@ import ( "context" "encoding/base64" "errors" + "fmt" "net/http" "net/url" "strconv" @@ -254,9 +255,14 @@ var ErrActionRunNotFound = errors.New("gitcode: no action run matched head_sha") // // Pass every documented filter that fits your intent — Branch plus Status // for a CI-failure diagnosis, for instance — to keep the scan short; an -// unpruned scan walks the repo's whole run history (capped at -// maxFindRunPages pages, then it returns the last error of exhaustion). -// Not-found surfaces as ErrActionRunNotFound (errors.Is). +// unpruned scan walks the repo's whole run history. The scan is bounded at +// maxFindRunPages pages of 100: a short page ends the walk — no hit in it +// means no hit anywhere, surfaced as ErrActionRunNotFound (errors.Is). +// Hitting the cap while pages keep coming back full means the target run +// may exist beyond the scanned window — that surfaces as an error wrapping +// ErrTooManyPages(与 Paginate 同一哨兵,issue #5 的纪律): +// 「截断」与「真的没有」可区分(issue #13),不再共用 +// ErrActionRunNotFound 出口把截断谎报成不存在。 func (c *Client) FindActionRunByHeadSHA(ctx context.Context, owner, repo, sha string, prune ListWorkflowRunsOptions) (*WorkflowRun, error) { if sha == "" { return nil, errors.New("gitcode: head sha is required") @@ -275,10 +281,14 @@ func (c *Client) FindActionRunByHeadSHA(ctx context.Context, owner, repo, sha st } // Short page ⇒ last page; no hit in it means no hit anywhere. if len(resp.WorkflowRuns) < 100 { - break + return nil, ErrActionRunNotFound } } - return nil, ErrActionRunNotFound + // 循环跑满且每一页都是满页:扫描触顶——目标运行可能落在窗口之外, + // 返回 ErrActionRunNotFound 会把「没扫到」谎报成「没有这条流水线」 + // (issue #13;同一仓的 Paginate 在完全相同的场景 yield ErrTooManyPages)。 + return nil, fmt.Errorf("%w after %d pages of %d items (head_sha scan truncated; absence cannot be claimed)", + ErrTooManyPages, maxFindRunPages, 100) } // WorkflowRunDetail is a run with its full stage → job → step tree. Pre diff --git a/client.go b/client.go index c57c0ea..370af09 100644 --- a/client.go +++ b/client.go @@ -383,28 +383,24 @@ func (c *Client) doRawBodyRequest(ctx context.Context, method, path string, body return c.doBufferedRequestAt(ctx, base, method, path, "application/json", raw, result, c.jsonBodyLimit()) } -// isNotFoundError checks if an error is a 404 Not Found response. +// isNotFoundError reports whether err is a 404 Not Found response, judged +// structurally (issue #12): a typed *NotFoundError (everything newAPIError +// maps a 404 to) or any *APIError carrying a 404 status code. The old +// string fallback — err.Error() containing the substring "404" — is gone: +// the APIError message embeds the request path and the response body, so a +// 403/429/500 on a route named "org404" (or a 500 whose body mentions 404) +// used to masquerade as Not Found and the boolean probes swallowed the +// real error. 判定只走 HTTP 状态码,与 CHANGELOG 宣传的结构化错误模型一致。 func isNotFoundError(err error) bool { if err == nil { return false } - if IsNotFound(err) { + var nf *NotFoundError + if errors.As(err, &nf) { return true } - return contains(err.Error(), "404") -} - -func contains(s, substr string) bool { - return len(s) >= len(substr) && searchString(s, substr) -} - -func searchString(s, substr string) bool { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return true - } - } - return false + var apiErr *APIError + return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound } // User represents a GitCode user. diff --git a/client_enhanced_test.go b/client_enhanced_test.go index 2457acb..c61b69b 100644 --- a/client_enhanced_test.go +++ b/client_enhanced_test.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/http/httptest" + "strings" "testing" ) @@ -157,7 +158,7 @@ func TestRequestHookError(t *testing.T) { t.Fatal("expected error from hook") } - if !contains(err.Error(), "hook rejected request") { + if !strings.Contains(err.Error(), "hook rejected request") { t.Errorf("expected hook error, got: %v", err) } } diff --git a/hardening_y4_test.go b/hardening_y4_test.go new file mode 100644 index 0000000..b397923 --- /dev/null +++ b/hardening_y4_test.go @@ -0,0 +1,249 @@ +package gitcode + +// Regression tests for issues #12-#14 (sweep lane Y4): structural 404 +// detection, scan-truncation distinguishability, and Multiplier default. + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +// --- issue #12: 404 probes must judge by status code, not message text --- + +// sweepY4ProbeCalls drives every public boolean probe that used to swallow +// errors on a "404" substring match (5 via isNotFoundError + 2 raw +// strings.Contains sites). Each gets path segments containing "404" so the +// OLD implementation would misjudge any status as Not Found. +func sweepY4ProbeCalls(c *Client) map[string]func() (bool, error) { + return map[string]func() (bool, error){ + "IsCollaborator": func() (bool, error) { return c.IsCollaborator(context.Background(), "org404", "repo", "user404") }, + "IsRepoAssignee": func() (bool, error) { return c.IsRepoAssignee(context.Background(), "org404", "repo", "user404") }, + "IsOrgPublicMember": func() (bool, error) { return c.IsOrgPublicMember(context.Background(), "org404", "user404") }, + "IsOrgBlockedUser": func() (bool, error) { return c.IsOrgBlockedUser(context.Background(), "org404", "user404") }, + "IsFollowing": func() (bool, error) { return c.IsFollowing(context.Background(), "user404") }, + "IsRepositoryStarred": func() (bool, error) { return c.IsRepositoryStarred(context.Background(), "org404", "repo404") }, + "IsPullRequestMerged": func() (bool, error) { return c.IsPullRequestMerged(context.Background(), "org404", "repo", 404) }, + } +} + +func TestSweepY4_Probes403With404InPathSurfacesError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"message":"insufficient permissions"}`) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + for name, call := range sweepY4ProbeCalls(c) { + t.Run(name, func(t *testing.T) { + ok, err := call() + if err == nil { + t.Fatalf("403 must surface (issue #12: it used to be swallowed as not-found on paths containing 404), got ok=%v err=nil", ok) + } + if ok { + t.Fatal("ok must be false on error") + } + if !IsForbidden(err) { + t.Fatalf("surfaced error should be the typed ForbiddenError, got %v", err) + } + }) + } +} + +func TestSweepY4_Probes500With404InBodySurfacesError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, `{"message":"upstream returned 404"}`) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + for name, call := range sweepY4ProbeCalls(c) { + t.Run(name, func(t *testing.T) { + ok, err := call() + if err == nil { + t.Fatalf("500 with a 404 substring in the body must surface, got ok=%v err=nil", ok) + } + if ok { + t.Fatal("ok must be false on error") + } + }) + } +} + +func TestSweepY4_ProbesReal404ReturnsFalseNil(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `{"message":"not found"}`) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + for name, call := range sweepY4ProbeCalls(c) { + t.Run(name, func(t *testing.T) { + ok, err := call() + if err != nil { + t.Fatalf("a genuine 404 still reads as (false, nil): %v", err) + } + if ok { + t.Fatal("ok must be false for not-found") + } + }) + } +} + +func TestSweepY4_IsNotFoundErrorStructural(t *testing.T) { + // 类型化 404:true + if !isNotFoundError(&NotFoundError{APIError: &APIError{StatusCode: http.StatusNotFound}}) { + t.Fatal("typed NotFoundError must match") + } + // 裸 APIError 携带 404 状态码:true(errors.As 分流) + if !isNotFoundError(&APIError{StatusCode: http.StatusNotFound, Message: "nope"}) { + t.Fatal("raw APIError with 404 status must match") + } + // 包装层:errors.As 要穿透 wrap + wrapped := fmt.Errorf("probe: %w", &NotFoundError{APIError: &APIError{StatusCode: http.StatusNotFound}}) + if !isNotFoundError(wrapped) { + t.Fatal("wrapped NotFoundError must match through errors.As") + } + // 非 404 一律 false——即使消息文本里带 "404"(旧实现的误判源) + if isNotFoundError(&ForbiddenError{APIError: &APIError{StatusCode: http.StatusForbidden, URL: "/repos/org404/repo"}}) { + t.Fatal("403 must NOT match, even with 404 in the URL") + } + if isNotFoundError(&APIError{StatusCode: http.StatusInternalServerError, Message: "upstream returned 404"}) { + t.Fatal("500 must NOT match, even with 404 in the body") + } + if isNotFoundError(errors.New("plain network error mentioning 404")) { + t.Fatal("non-API errors must NOT match on message text") + } + if isNotFoundError(nil) { + t.Fatal("nil must not match") + } +} + +// --- issue #13: scan truncation must not masquerade as not-found --- + +func fullRunsPage(n int, sha string) string { + body := `{"total_count":99999,"workflow_runs":[` + for i := 0; i < n; i++ { + if i > 0 { + body += "," + } + body += fmt.Sprintf(`{"workflow_run_id":"%d","status":"COMPLETED","head_sha":"other-sha-%d"}`, i, i) + } + return body + `]}` +} + +func TestSweepY4_FindActionRunByHeadSHA_TruncatedScanIsDistinguishable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, fullRunsPage(100, "target-sha")) // 恒返满页:游走必然触顶 + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + _, err := c.FindActionRunByHeadSHA(context.Background(), "o", "r", "target-sha", ListWorkflowRunsOptions{}) + if err == nil { + t.Fatal("a capped scan must not end silently") + } + if !errors.Is(err, ErrTooManyPages) { + t.Fatalf("err = %v, want errors.Is(err, ErrTooManyPages) — same sentinel as Paginate (issue #5 discipline)", err) + } + if errors.Is(err, ErrActionRunNotFound) { + t.Fatal("a truncated scan must NOT surface as ErrActionRunNotFound — 'not scanned' is not 'does not exist'") + } +} + +func TestSweepY4_FindActionRunByHeadSHA_ShortPageStillNotFound(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"total_count":1,"workflow_runs":[{"workflow_run_id":"1","status":"COMPLETED","head_sha":"other-sha"}]}`) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + _, err := c.FindActionRunByHeadSHA(context.Background(), "o", "r", "target-sha", ListWorkflowRunsOptions{}) + if !errors.Is(err, ErrActionRunNotFound) { + t.Fatalf("short-page exhaustion should stay ErrActionRunNotFound, got %v", err) + } +} + +func TestSweepY4_FindActionRunByHeadSHA_HitOnLaterPage(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Query().Get("page") == "2" { + fmt.Fprint(w, `{"total_count":150,"workflow_runs":[{"workflow_run_id":"42","status":"COMPLETED","head_sha":"target-sha"}]}`) + return + } + fmt.Fprint(w, fullRunsPage(100, "target-sha")) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + run, err := c.FindActionRunByHeadSHA(context.Background(), "o", "r", "target-sha", ListWorkflowRunsOptions{}) + if err != nil { + t.Fatalf("hit on page 2 must be returned: %v", err) + } + if run == nil || run.WorkflowRunID != "42" { + t.Fatalf("wrong run: %+v", run) + } +} + +// --- issue #14: unset Multiplier must not collapse backoff to zero --- + +func TestSweepY4_RetryPolicyMultiplierDefault(t *testing.T) { + // 对照:显式 2.0 与漏填的退避序列必须一致(文档缺省 2.0 归一) + gap := func(policy RetryPolicy) []time.Duration { + var attempts int + var stamps []time.Time + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts++ + stamps = append(stamps, time.Now()) + w.WriteHeader(http.StatusServiceUnavailable) + fmt.Fprint(w, `{"message":"down"}`) + })) + defer srv.Close() + + c := NewClientWithBaseURL(srv.URL+"/api/v5", "tok") + policy.RetryableStatusCodes = []int{503} + c.SetRetryPolicy(policy) + _, _ = c.GetCurrentUser(context.Background()) + var gaps []time.Duration + for i := 1; i < len(stamps); i++ { + gaps = append(gaps, stamps[i].Sub(stamps[i-1])) + } + return gaps + } + + unset := gap(RetryPolicy{MaxRetries: 2, InitialBackoff: 200 * time.Millisecond}) + explicit := gap(RetryPolicy{MaxRetries: 2, InitialBackoff: 200 * time.Millisecond, Multiplier: 2.0}) + if len(unset) != 2 || len(explicit) != 2 { + t.Fatalf("attempts = %d/%d, want 2 gaps each", len(unset), len(explicit)) + } + for i := range unset { + if unset[i] <= 0 { + t.Fatalf("issue #14 regression: retry %d gap = %v with unset Multiplier (backoff collapsed to zero, busy-wait)", i+1, unset[i]) + } + // 归一后漏填 ≈ 显式 2.0(±抖动余量) + if unset[i] < explicit[i]/2 || unset[i] > explicit[i]*2 { + t.Fatalf("retry %d gap: unset=%v explicit=%v — should match the documented 2.0 default", i+1, unset[i], explicit[i]) + } + } + if !(unset[1] > unset[0]) { + t.Fatalf("backoff must grow exponentially: %v vs %v", unset[0], unset[1]) + } + + // Multiplier=1.0 是合法显式选择(恒定退避),不得被归一吞掉 + constant := gap(RetryPolicy{MaxRetries: 2, InitialBackoff: 200 * time.Millisecond, Multiplier: 1.0}) + if constant[1] > constant[0]*3/2 { + t.Fatalf("Multiplier=1.0 should give constant backoff: %v then %v", constant[0], constant[1]) + } +} diff --git a/pulls.go b/pulls.go index b0d7def..d4abfb9 100644 --- a/pulls.go +++ b/pulls.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "net/http" - "strings" "time" ) @@ -215,7 +214,7 @@ func (c *Client) MergePullRequest(ctx context.Context, owner, repo string, numbe func (c *Client) IsPullRequestMerged(ctx context.Context, owner, repo string, number int) (bool, error) { _, err := c.doRawRequest(ctx, http.MethodGet, pathf("/repos/%s/%s/pulls/%d/merge", owner, repo, number)) if err != nil { - if strings.Contains(err.Error(), "404") { + if isNotFoundError(err) { return false, nil } return false, err diff --git a/retry.go b/retry.go index 08d2676..aca84c2 100644 --- a/retry.go +++ b/retry.go @@ -62,12 +62,16 @@ func (c *Client) shouldRetry(statusCode int) bool { return false } -// defaultInitialBackoff / defaultMaxBackoff fill in the documented defaults -// when a custom policy leaves the corresponding field unset (issue #4: a -// zero MaxBackoff used to clamp every wait to 0). +// defaultInitialBackoff / defaultMaxBackoff / defaultMultiplier fill in the +// documented defaults when a custom policy leaves the corresponding field +// unset (issue #4: a zero MaxBackoff used to clamp every wait to 0; +// issue #14: a zero Multiplier made math.Pow(0, n>0) = 0 — every retry +// after the first had zero backoff, the busy-wait pathology #4 fixed +// re-entering through another path). const ( defaultInitialBackoff = 1 * time.Second defaultMaxBackoff = 30 * time.Second + defaultMultiplier = 2.0 ) // maxRetryAfterSeconds bounds delay-seconds before the Duration conversion @@ -130,6 +134,10 @@ func (c *Client) getRetryWaitTime(attempt int, resp *http.Response) time.Duratio if maxBackoff <= 0 { maxBackoff = defaultMaxBackoff } + multiplier := policy.Multiplier + if multiplier <= 0 { + multiplier = defaultMultiplier // 1.0(恒定退避)是合法显式选择,仅归一未填的零值 + } // Check Retry-After header first (for 429 responses): a valid // server-provided delay wins over the exponential curve, but shares @@ -139,7 +147,7 @@ func (c *Client) getRetryWaitTime(attempt int, resp *http.Response) time.Duratio } // Exponential backoff - backoff := time.Duration(float64(initial) * math.Pow(policy.Multiplier, float64(attempt))) + backoff := time.Duration(float64(initial) * math.Pow(multiplier, float64(attempt))) return min(backoff, maxBackoff) } diff --git a/types.go b/types.go index a797c6c..7df0ebc 100644 --- a/types.go +++ b/types.go @@ -221,7 +221,7 @@ func (c *Client) UnstarRepository(ctx context.Context, owner, repo string) error func (c *Client) IsRepositoryStarred(ctx context.Context, owner, repo string) (bool, error) { _, err := c.doRawRequest(ctx, http.MethodGet, pathf("/user/starred/%s/%s", owner, repo)) if err != nil { - if strings.Contains(err.Error(), "404") { + if isNotFoundError(err) { return false, nil } return false, err From 6982023aec403f045f56fed69def635d59cd5b3d Mon Sep 17 00:00:00 2001 From: MurphyYi Date: Fri, 13 Nov 2026 01:18:23 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(lint):=20hardening=5Fy4=5Ftest.go=20240?= =?UTF-8?q?=20=E8=A1=8C=20De=20Morgan=20=E5=BD=A2=E5=BC=8F=EF=BC=88staticc?= =?UTF-8?q?heck=20QF1001=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hardening_y4_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hardening_y4_test.go b/hardening_y4_test.go index b397923..b26a861 100644 --- a/hardening_y4_test.go +++ b/hardening_y4_test.go @@ -237,7 +237,7 @@ func TestSweepY4_RetryPolicyMultiplierDefault(t *testing.T) { t.Fatalf("retry %d gap: unset=%v explicit=%v — should match the documented 2.0 default", i+1, unset[i], explicit[i]) } } - if !(unset[1] > unset[0]) { + if unset[1] <= unset[0] { t.Fatalf("backoff must grow exponentially: %v vs %v", unset[0], unset[1]) }