Skip to content

Commit 8feb77b

Browse files
authored
[INT-718] Add TargetNotFoundError for targeted scan targets missing from the source (#5123)
* Add TargetNotFoundError for targeted scan targets missing from the source * Check download response status in exact-path retry
1 parent 09c9107 commit 8feb77b

4 files changed

Lines changed: 247 additions & 1 deletion

File tree

pkg/sources/errors.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,22 @@ func (t TargetedScanError) Error() string {
7474
func (t TargetedScanError) Unwrap() error {
7575
return t.Err
7676
}
77+
78+
// TargetNotFoundError indicates a targeted scan failed because the requested
79+
// target is definitively absent from the source (e.g. the file, commit, or
80+
// message it pointed to was deleted), as opposed to inaccessible due to
81+
// authorization or transient failures. Consumers can treat this as terminal:
82+
// retrying cannot succeed until a fresh scan updates the stored location.
83+
type TargetNotFoundError struct {
84+
Err error
85+
}
86+
87+
var _ error = (*TargetNotFoundError)(nil)
88+
89+
func (t TargetNotFoundError) Error() string {
90+
return t.Err.Error()
91+
}
92+
93+
func (t TargetNotFoundError) Unwrap() error {
94+
return t.Err
95+
}

pkg/sources/errors_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,19 @@ func TestScanErrorsString(t *testing.T) {
159159
t.Errorf("got %q, want %q", got, want)
160160
}
161161
}
162+
163+
func TestTargetNotFoundErrorUnwrapsThroughJobChain(t *testing.T) {
164+
inner := &TargetNotFoundError{Err: fmt.Errorf("could not download file for scan: 404")}
165+
// The chain a targeted scan failure travels before a consumer sees it:
166+
// scanTargets wraps in TargetedScanError, the source manager wraps in
167+
// Fatal, and JobProgressMetrics.FatalErrors joins the results.
168+
chain := errors.Join(Fatal{&TargetedScanError{Err: inner, SecretID: 42}})
169+
170+
var tnf *TargetNotFoundError
171+
if !errors.As(chain, &tnf) {
172+
t.Fatal("TargetNotFoundError not found in wrapped chain")
173+
}
174+
if tnf.Error() != inner.Error() {
175+
t.Fatalf("unexpected message: %q", tnf.Error())
176+
}
177+
}

pkg/sources/github/github.go

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2214,7 +2214,30 @@ func (s *Source) scanTarget(ctx context.Context, target sources.ChunkingTarget,
22142214
defer func() { _ = resp.Body.Close() }()
22152215
}
22162216
if err != nil {
2217-
return fmt.Errorf("could not download file for scan: %w", err)
2217+
// DownloadContents locates the file by listing its parent directory,
2218+
// and the contents API caps listings at 1000 entries, so it can fail
2219+
// for files that exist. Retry with an exact-path lookup, which also
2220+
// serves as the existence probe when it fails.
2221+
retryCloser, retryResp, retryErr := s.downloadContentsByPath(
2222+
ctx, apiClient, segments[1], segments[2], meta.GetFile(), meta.GetCommit())
2223+
if retryResp != nil && retryResp.Response != nil && retryResp.Body != nil {
2224+
defer func() { _ = retryResp.Body.Close() }()
2225+
}
2226+
if retryErr != nil {
2227+
wrapped := fmt.Errorf("could not download file for scan: %w", retryErr)
2228+
// The exact-path lookup 404ing is authoritative for the path, but
2229+
// GitHub also returns 404 for existing resources the credentials
2230+
// cannot see, so only classify the target as gone when the
2231+
// repository itself is still reachable with the same client.
2232+
if retryResp != nil && retryResp.Response != nil &&
2233+
retryResp.StatusCode == http.StatusNotFound &&
2234+
s.repoReachable(ctx, apiClient, segments[1], segments[2]) {
2235+
return &sources.TargetNotFoundError{Err: wrapped}
2236+
}
2237+
return wrapped
2238+
}
2239+
fileCtx := context.WithValues(ctx, "path", meta.GetFile())
2240+
return handlers.HandleFile(fileCtx, retryCloser, &chunkSkel, reporter)
22182241
}
22192242
if resp.StatusCode != http.StatusOK {
22202243
return fmt.Errorf("unexpected HTTP response status when trying to download file for scan: %v", resp.Status)
@@ -2224,6 +2247,44 @@ func (s *Source) scanTarget(ctx context.Context, target sources.ChunkingTarget,
22242247
return handlers.HandleFile(fileCtx, readCloser, &chunkSkel, reporter)
22252248
}
22262249

2250+
// downloadContentsByPath fetches a file the same way DownloadContents does,
2251+
// but resolves it with an exact-path contents lookup instead of searching a
2252+
// directory listing, so it is immune to the 1000-entry listing cap. On
2253+
// failure the returned response is always the exact-path lookup's, whose 404
2254+
// is an authoritative statement about the path at that ref; a failure of the
2255+
// download itself must not be mistaken for the target being gone, because
2256+
// the lookup just proved it exists.
2257+
func (s *Source) downloadContentsByPath(ctx context.Context, apiClient *github.Client, owner, repo, filePath, ref string) (io.ReadCloser, *github.Response, error) {
2258+
fileContent, _, resp, err := apiClient.Repositories.GetContents(
2259+
ctx, owner, repo, filePath, &github.RepositoryContentGetOptions{Ref: ref})
2260+
if err != nil {
2261+
return nil, resp, err
2262+
}
2263+
if fileContent == nil || fileContent.GetDownloadURL() == "" {
2264+
return nil, resp, fmt.Errorf("no download link found for %s", filePath)
2265+
}
2266+
dlReq, err := http.NewRequestWithContext(ctx, http.MethodGet, fileContent.GetDownloadURL(), nil)
2267+
if err != nil {
2268+
return nil, resp, err
2269+
}
2270+
dlResp, err := apiClient.Client().Do(dlReq)
2271+
if err != nil {
2272+
return nil, resp, err
2273+
}
2274+
if dlResp.StatusCode != http.StatusOK {
2275+
_ = dlResp.Body.Close()
2276+
return nil, resp, fmt.Errorf("unexpected HTTP response status when trying to download file for scan: %v", dlResp.Status)
2277+
}
2278+
return dlResp.Body, &github.Response{Response: dlResp}, nil
2279+
}
2280+
2281+
// repoReachable reports whether the repository is still visible with the
2282+
// same client.
2283+
func (s *Source) repoReachable(ctx context.Context, apiClient *github.Client, owner, repo string) bool {
2284+
_, resp, err := apiClient.Repositories.Get(ctx, owner, repo)
2285+
return err == nil && resp != nil && resp.StatusCode == http.StatusOK
2286+
}
2287+
22272288
func (s *Source) scanWikiTarget(ctx context.Context, wikiURL string, meta *source_metadatapb.Github, chunkSkel *sources.Chunk, reporter sources.ChunkReporter) error {
22282289
if meta.GetCommit() == "" {
22292290
return fmt.Errorf("wiki target has no commit")
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
package github
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"net/url"
9+
"testing"
10+
11+
"github.com/google/go-github/v67/github"
12+
"github.com/stretchr/testify/assert"
13+
14+
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
15+
)
16+
17+
func testClientForServer(t *testing.T, serverURL string) *github.Client {
18+
t.Helper()
19+
client := github.NewClient(nil)
20+
base, err := url.Parse(serverURL + "/")
21+
assert.NoError(t, err)
22+
client.BaseURL = base
23+
return client
24+
}
25+
26+
// downloadByPathServer answers the exact-path contents lookup, the raw
27+
// download it points at, and the repository lookup repoReachable makes.
28+
func downloadByPathServer(t *testing.T, fileStatus, rawStatus, repoStatus int) *httptest.Server {
29+
t.Helper()
30+
var server *httptest.Server
31+
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
32+
switch r.URL.Path {
33+
case "/repos/o/r/contents/dir/f.txt":
34+
w.Header().Set("Content-Type", "application/json")
35+
w.WriteHeader(fileStatus)
36+
if fileStatus == http.StatusOK {
37+
_, _ = fmt.Fprintf(w, `{"type":"file","name":"f.txt","path":"dir/f.txt","download_url":"%s/raw/dir/f.txt"}`, server.URL)
38+
return
39+
}
40+
_, _ = w.Write([]byte(`{"message":"Not Found"}`))
41+
case "/raw/dir/f.txt":
42+
w.WriteHeader(rawStatus)
43+
if rawStatus == http.StatusOK {
44+
_, _ = w.Write([]byte("file body"))
45+
return
46+
}
47+
_, _ = w.Write([]byte("raw host error page"))
48+
case "/repos/o/r":
49+
w.Header().Set("Content-Type", "application/json")
50+
w.WriteHeader(repoStatus)
51+
if repoStatus == http.StatusOK {
52+
_, _ = w.Write([]byte(`{"id":1,"name":"r","full_name":"o/r"}`))
53+
return
54+
}
55+
_, _ = w.Write([]byte(`{"message":"Not Found"}`))
56+
default:
57+
t.Errorf("unexpected request: %s", r.URL.Path)
58+
w.WriteHeader(http.StatusInternalServerError)
59+
}
60+
}))
61+
return server
62+
}
63+
64+
func TestDownloadContentsByPathFetchesFileBody(t *testing.T) {
65+
server := downloadByPathServer(t, http.StatusOK, http.StatusOK, http.StatusOK)
66+
defer server.Close()
67+
68+
s := &Source{}
69+
client := testClientForServer(t, server.URL)
70+
rc, resp, err := s.downloadContentsByPath(context.Background(), client, "o", "r", "dir/f.txt", "abc123")
71+
assert.NoError(t, err)
72+
assert.Equal(t, http.StatusOK, resp.StatusCode)
73+
body, err := io.ReadAll(rc)
74+
assert.NoError(t, err)
75+
assert.NoError(t, rc.Close())
76+
assert.Equal(t, "file body", string(body))
77+
}
78+
79+
func TestDownloadContentsByPathReturns404Response(t *testing.T) {
80+
server := downloadByPathServer(t, http.StatusNotFound, http.StatusOK, http.StatusOK)
81+
defer server.Close()
82+
83+
s := &Source{}
84+
client := testClientForServer(t, server.URL)
85+
rc, resp, err := s.downloadContentsByPath(context.Background(), client, "o", "r", "dir/f.txt", "abc123")
86+
assert.Error(t, err)
87+
assert.Nil(t, rc)
88+
// The 404 is the exact-path lookup's, which the caller combines with
89+
// repoReachable to classify the target as gone.
90+
assert.NotNil(t, resp)
91+
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
92+
}
93+
94+
func TestDownloadContentsByPathNon404Failure(t *testing.T) {
95+
server := downloadByPathServer(t, http.StatusForbidden, http.StatusOK, http.StatusOK)
96+
defer server.Close()
97+
98+
s := &Source{}
99+
client := testClientForServer(t, server.URL)
100+
_, resp, err := s.downloadContentsByPath(context.Background(), client, "o", "r", "dir/f.txt", "abc123")
101+
assert.Error(t, err)
102+
assert.NotNil(t, resp)
103+
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
104+
}
105+
106+
func TestRepoReachable(t *testing.T) {
107+
server := downloadByPathServer(t, http.StatusNotFound, http.StatusOK, http.StatusOK)
108+
defer server.Close()
109+
110+
s := &Source{}
111+
client := testClientForServer(t, server.URL)
112+
assert.True(t, s.repoReachable(context.Background(), client, "o", "r"))
113+
}
114+
115+
func TestRepoNotReachable(t *testing.T) {
116+
server := downloadByPathServer(t, http.StatusNotFound, http.StatusOK, http.StatusNotFound)
117+
defer server.Close()
118+
119+
s := &Source{}
120+
client := testClientForServer(t, server.URL)
121+
// The repo 404s too: could be lost access rather than deletion, so the
122+
// caller must not classify the target as gone.
123+
assert.False(t, s.repoReachable(context.Background(), client, "o", "r"))
124+
}
125+
126+
func TestRepoReachableServerDown(t *testing.T) {
127+
server := downloadByPathServer(t, http.StatusNotFound, http.StatusOK, http.StatusOK)
128+
server.Close()
129+
130+
s := &Source{}
131+
client := testClientForServer(t, server.URL)
132+
assert.False(t, s.repoReachable(context.Background(), client, "o", "r"))
133+
}
134+
135+
func TestDownloadContentsByPathNon200Download(t *testing.T) {
136+
server := downloadByPathServer(t, http.StatusOK, http.StatusInternalServerError, http.StatusOK)
137+
defer server.Close()
138+
139+
s := &Source{}
140+
client := testClientForServer(t, server.URL)
141+
rc, resp, err := s.downloadContentsByPath(context.Background(), client, "o", "r", "dir/f.txt", "abc123")
142+
assert.Error(t, err)
143+
assert.ErrorContains(t, err, "unexpected HTTP response status")
144+
assert.Nil(t, rc)
145+
// The returned response is the exact-path lookup's (200), not the failed
146+
// download's, so the caller cannot mistake a download failure for the
147+
// target being gone.
148+
assert.NotNil(t, resp)
149+
assert.Equal(t, http.StatusOK, resp.StatusCode)
150+
}

0 commit comments

Comments
 (0)