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
20 changes: 15 additions & 5 deletions actions_v8.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -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")
Expand All @@ -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
Expand Down
28 changes: 12 additions & 16 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion client_enhanced_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

Expand Down Expand Up @@ -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)
}
}
Expand Down
249 changes: 249 additions & 0 deletions hardening_y4_test.go
Original file line number Diff line number Diff line change
@@ -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])
}
}
3 changes: 1 addition & 2 deletions pulls.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"net/http"
"strings"
"time"
)

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading