diff --git a/attributes.go b/attributes.go index dcbb853..0409440 100644 --- a/attributes.go +++ b/attributes.go @@ -3,6 +3,7 @@ package cinc import ( "bytes" "encoding/json" + "errors" ) // Attributes is a free-form Chef attribute tree. It marshals as a plain JSON @@ -33,6 +34,9 @@ func decodeObject(b []byte) (map[string]any, error) { if err := dec.Decode(&m); err != nil { return nil, err } + if dec.More() { + return nil, errors.New("cinc: unexpected data after the JSON object") + } return m, nil } diff --git a/cookbooks.go b/cookbooks.go index aef525f..1ec672d 100644 --- a/cookbooks.go +++ b/cookbooks.go @@ -11,6 +11,7 @@ import ( "net/http" "os" "path/filepath" + "runtime" "slices" "strings" ) @@ -324,6 +325,19 @@ func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, dest } jobs[i] = fileDownload{url: ref.URL, rel: rel, path: ref.Path, checksum: ref.Checksum} } + // Two entries that land on one file would race two writers onto it, one + // silently winning: refuse them before anything is written. + seen := make(map[string]string, len(jobs)) + for _, j := range jobs { + key := filepath.Clean(j.rel) + if caseInsensitiveFS() { + key = strings.ToLower(key) + } + if other, dup := seen[key]; dup { + return fmt.Errorf("cinc: cookbook manifest paths %q and %q are the same file on this system", other, j.path) + } + seen[key] = j.path + } if err := os.MkdirAll(destDir, 0o755); err != nil { return fmt.Errorf("cinc: create dirs: %w", err) } @@ -344,6 +358,13 @@ func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, dest }) } +// caseInsensitiveFS reports whether this platform's default filesystems fold +// case (macOS's APFS and HFS+, Windows's NTFS), so that paths differing only +// in case are one file. +func caseInsensitiveFS() bool { + return runtime.GOOS == "darwin" || runtime.GOOS == "windows" +} + // downloadFile GETs a pre-signed bookshelf URL (no Chef signing) and writes // the body to rel under root, creating parent directories as needed. // diff --git a/defensive_test.go b/defensive_test.go new file mode 100644 index 0000000..1b9e357 --- /dev/null +++ b/defensive_test.go @@ -0,0 +1,206 @@ +package cinc + +import ( + "context" + "io" + "math" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "sync/atomic" + "testing" +) + +// A request path with an empty, "." or ".." segment never reaches the server. +// The server's router drops an empty trailing segment, so an empty item id +// would turn DELETE /data// into DELETE /data/: the whole bag. +func TestRequestPath_RefusesEmptyAndDotSegments(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Write([]byte(`{}`)) + })) + defer srv.Close() + c := newTestClient(t, srv) + ctx := context.Background() + + for name, call := range map[string]func() error{ + "empty item id": func() error { _, err := c.DataBags.Items("b").Delete(ctx, ""); return err }, + "dot item id": func() error { _, err := c.DataBags.Items("b").Delete(ctx, "."); return err }, + "dot-dot node": func() error { _, _, err := c.Nodes.Get(ctx, ".."); return err }, + "empty bag": func() error { _, err := c.DataBags.Items("").Delete(ctx, "x"); return err }, + "empty node": func() error { _, err := c.Nodes.Delete(ctx, ""); return err }, + "Do double slash": func() error { _, _, err := c.Do(ctx, "GET", "/organizations/o//nodes", nil); return err }, + "Do dot segment": func() error { _, _, err := c.Do(ctx, "GET", "/organizations/o/nodes/../x", nil); return err }, + } { + err := call() + if err == nil || !strings.Contains(err.Error(), "path segment") { + t.Errorf("%s: err = %v, want a path segment error", name, err) + } + } + if n := hits.Load(); n != 0 { + t.Errorf("%d requests reached the server", n) + } + + // A query string may hold anything, and a name that merely contains dots + // is a name. + if _, _, err := c.Do(ctx, "GET", "/organizations/o/search/node?q=a//b/..", nil); err != nil { + t.Errorf("query with slashes and dots: %v", err) + } + if _, _, err := c.Nodes.Get(ctx, "web..01"); err != nil { + t.Errorf("dotted name: %v", err) + } +} + +// Every Chef GET answers with a JSON document. A 2xx with an empty or null +// body (a misbehaving proxy or cache) must not decode as an empty object: +// Groups.AddMembers and ACLs.Grant would write that back, dropping every +// existing member, and Users.SetPassword would panic on the nil map. +func TestGET_EmptyBodyIsAnError(t *testing.T) { + for _, body := range []string{"", "null", " null\n"} { + var puts atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + puts.Add(1) + } + w.Write([]byte(body)) + })) + c := newTestClient(t, srv) + ctx := context.Background() + + if _, err := c.Groups.AddMembers(ctx, "admins", MemberUser, "bob"); err == nil { + t.Errorf("body %q: Groups.AddMembers succeeded", body) + } + if _, err := c.ACLs.Grant(ctx, ObjectACL(ACLNodes, "web"), "read", ACLMembers{Users: []string{"bob"}}); err == nil { + t.Errorf("body %q: ACLs.Grant succeeded", body) + } + if _, err := c.Users.SetPassword(ctx, "bob", "pw"); err == nil { + t.Errorf("body %q: Users.SetPassword succeeded", body) + } + if _, _, err := c.Nodes.Get(ctx, "web"); err == nil || !strings.Contains(err.Error(), "empty") { + t.Errorf("body %q: Nodes.Get err = %v, want an empty-body error", body, err) + } + if n := puts.Load(); n != 0 { + t.Errorf("body %q: %d writes reached the server", body, n) + } + srv.Close() + } + + // A write may answer with nothing: that is not an error. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})) + defer srv.Close() + if _, err := newTestClient(t, srv).Nodes.Delete(context.Background(), "web"); err != nil { + t.Errorf("DELETE with an empty body: %v", err) + } +} + +// A server whose total promises rows it never returns must not keep the +// iterator paging for ever: a run of empty pages is an error, not silence, +// since stopping quietly would truncate the results. +func TestSearch_EmptyPagesDoNotRunForever(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Write([]byte(`{"total":1000000000000,"start":0,"rows":[]}`)) + })) + defer srv.Close() + _, err := newTestClient(t, srv).Search.Collect(context.Background(), "node", "*:*", WithRows(10)) + if err == nil || !strings.Contains(err.Error(), "empty pages") { + t.Errorf("err = %v, want an empty-pages error", err) + } + if n := hits.Load(); n != maxEmptySearchPages { + t.Errorf("requests = %d, want %d", n, maxEmptySearchPages) + } +} + +// The next offset cannot overflow into a negative start. +func TestSearch_HugeRowsDoNotOverflow(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Write([]byte(`{"total":1000000000000,"start":1,"rows":[{"name":"a"}]}`)) + })) + defer srv.Close() + rows, err := newTestClient(t, srv).Search.Collect(context.Background(), "node", "*:*", WithStart(1), WithRows(math.MaxInt)) + if err != nil || len(rows) != 1 || hits.Load() != 1 { + t.Errorf("Collect = %d rows, %v after %d requests; want 1 row from 1 request", len(rows), err, hits.Load()) + } +} + +// Two manifest entries that land on one file would race two writers onto it, +// one silently winning. Paths equal once cleaned always collide; paths equal +// but for case collide on the case-insensitive filesystems macOS and Windows +// use by default. +func TestDownloadFiles_RefusesCollidingPaths(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + t.Error("nothing should be fetched") + })) + defer srv.Close() + c := newTestClient(t, srv) + ref := func(p string) CookbookFileRef { return CookbookFileRef{Path: p, URL: srv.URL + "/f"} } + + err := c.Cookbooks.DownloadFiles(context.Background(), + &Cookbook{AllFilesManifest: []CookbookFileRef{ref("recipes/x.rb"), ref("recipes/./x.rb")}}, t.TempDir()) + if err == nil || !strings.Contains(err.Error(), "same file") { + t.Errorf("cleaned duplicate: err = %v, want a same-file error", err) + } + + // On a case-sensitive filesystem the two are distinct files, which + // download normally, so only check the refusal where case folds. + if caseInsensitiveFS() { + err = c.Cookbooks.DownloadFiles(context.Background(), + &Cookbook{AllFilesManifest: []CookbookFileRef{ref("recipes/default.rb"), ref("recipes/DEFAULT.rb")}}, t.TempDir()) + if err == nil || !strings.Contains(err.Error(), "same file") { + t.Errorf("case-fold duplicate on %s: err = %v, want a same-file error", runtime.GOOS, err) + } + } +} + +// A decrypted value is one JSON document; trailing bytes mean it is corrupt. +func TestDecrypt_RejectsTrailingData(t *testing.T) { + if _, err := unboxValue([]byte(`{"json_wrapper":1} junk`)); err == nil { + t.Error("unboxValue accepted trailing data") + } +} + +// An S3 or bookshelf error body can echo the request's credentials +// (SignatureDoesNotMatch includes the canonical request and the provided +// signature); only its Code and Message belong in an error. +func TestTransferError_KeepsOnlyS3CodeAndMessage(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(` +SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided.AKIAEXAMPLEGET /x X-Amz-Credential=AKIAEXAMPLE%2Fsecret X-Amz-Security-Token=tokdeadbeef`)) + })) + defer srv.Close() + c := newTestClient(t, srv) + recordSleeps(c) + err := c.Fetch(context.Background(), srv.URL+"/x", func(io.Reader) error { return nil }) + if err == nil || !strings.Contains(err.Error(), "SignatureDoesNotMatch: The request signature") { + t.Fatalf("err = %v, want the S3 code and message", err) + } + for _, secret := range []string{"AKIAEXAMPLE", "Security-Token", "deadbeef"} { + if strings.Contains(err.Error(), secret) { + t.Errorf("err leaks %q: %v", secret, err) + } + } +} + +// A body that is not a Chef error (a proxy's HTML page) is kept, but capped. +func TestErrorResponse_CapsRawBody(t *testing.T) { + er := newErrorResponse("GET", "/x", 502, []byte(strings.Repeat("x", 100_000))) + if n := len(er.ServerMessage()); n > maxRawErrorBody+len("…") { + t.Errorf("message is %d bytes, want at most %d", n, maxRawErrorBody) + } +} + +// truncate never cuts a multi-byte character in half. +func TestTruncate_RuneBoundary(t *testing.T) { + if got := truncate("ab€", 3); got != "ab…" { // € is 3 bytes: cutting at 3 would split it + t.Errorf("truncate = %q, want %q", got, "ab…") + } + if got := truncate("abc", 3); got != "abc" { + t.Errorf("truncate = %q, want it unchanged", got) + } +} diff --git a/errors.go b/errors.go index c6d5e22..afe3e3c 100644 --- a/errors.go +++ b/errors.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "unicode/utf8" ) // Sentinel errors for use with errors.Is. @@ -106,11 +107,27 @@ func newErrorResponse(method, path string, code int, body []byte) *ErrorResponse } } if len(er.Messages) == 0 && len(body) > 0 { - er.Messages = []string{strings.TrimSpace(string(body))} + er.Messages = []string{truncate(strings.TrimSpace(string(body)), maxRawErrorBody)} } return er } +// maxRawErrorBody caps an error body that is not a Chef error document (a +// proxy's HTML page, say), so it cannot bloat an error message or a log. +const maxRawErrorBody = 512 + +// truncate returns s cut to at most n bytes, on a rune boundary, with an +// ellipsis when anything was cut. +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + for n > 0 && !utf8.RuneStart(s[n]) { + n-- + } + return s[:n] + "…" +} + // errorText returns the text of one element of an erchef "error" value: a // string, or an object's "message". func errorText(raw json.RawMessage) string { diff --git a/search.go b/search.go index 6d44371..f1137d6 100644 --- a/search.go +++ b/search.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "iter" + "math" "net/url" "strconv" "strings" @@ -275,12 +276,18 @@ func (s *SearchService) Collect(ctx context.Context, index, query string, opts . // eachPage is the single paging loop behind All and Collect. It requests // successive pages and calls fn with each one and the offset it was // requested at; fn returns false to stop without fetching further pages. +// maxEmptySearchPages is how many empty pages in a row end a search with an +// error. One empty page is normal (every object on it was deleted since it +// was indexed); a long run means Total promises rows the server never sends. +const maxEmptySearchPages = 10 + func (s *SearchService) eachPage(ctx context.Context, index, query string, opts []SearchOption, fn func(res *SearchResult, offset int) bool) error { p := searchParams{rows: 1000} for _, o := range opts { o(&p) } offset := p.start + empty := 0 for { res, _, err := s.Query(ctx, index, query, WithStart(offset), WithRows(p.rows), WithPartial(p.partial)) @@ -294,9 +301,18 @@ func (s *SearchService) eachPage(ctx context.Context, index, query string, opts // the server drops objects deleted since they were indexed from a // page, while Total still counts them. A short or empty page is not // the end (chef-client's Search::Query pages the same way). + if p.rows <= 0 || offset > math.MaxInt-p.rows { + return nil + } offset += p.rows - if p.rows <= 0 || offset >= res.Total { + if offset >= res.Total { return nil } + if len(res.Rows) > 0 { + empty = 0 + } else if empty++; empty >= maxEmptySearchPages { + return fmt.Errorf("cinc: search %s %q: %d empty pages in a row at start %d of a reported total of %d; the results are incomplete", + index, query, empty, offset, res.Total) + } } } diff --git a/transport.go b/transport.go index 913464f..8c7ed03 100644 --- a/transport.go +++ b/transport.go @@ -13,6 +13,7 @@ import ( "math/rand/v2" "net/http" "net/url" + "regexp" "strconv" "strings" "time" @@ -40,6 +41,9 @@ const maxBackoff = 10 * time.Second // Every attempt goes through doOnce, so a retry resends the same body and is // signed afresh with a new timestamp. func (c *Client) doRaw(ctx context.Context, method, path string, body []byte) ([]byte, *Response, error) { + if err := checkPathSegments(path); err != nil { + return nil, nil, err + } for attempt := 0; ; attempt++ { data, resp, err := c.doOnce(ctx, method, path, body) status := 0 @@ -68,6 +72,21 @@ func giveUp(ctx context.Context, err error) error { return err } +// checkPathSegments refuses a request path (before any query) with an empty, +// "." or ".." segment. Every one comes from an empty or dot name, and none is +// harmless: the server's router drops an empty trailing segment, so DELETE +// /data// (an empty item id) would delete the whole bag, and a dot +// segment names a different object to any proxy that normalizes the path. +func checkPathSegments(path string) error { + p, _, _ := strings.Cut(path, "?") + for seg := range strings.SplitSeq(strings.TrimPrefix(p, "/"), "/") { + if seg == "" || seg == "." || seg == ".." { + return fmt.Errorf("cinc: request path %q has an empty, \".\" or \"..\" path segment; is a name empty?", path) + } + } + return nil +} + // retryable reports whether a signed request that ended with status and err // may be sent again. A GET may repeat any transient failure (shouldRetry). // Any other method may repeat only a 503: the server refused the request @@ -171,14 +190,38 @@ func (c *Client) transferOnce(newReq func() (*http.Request, error), handle func( } return 0, nil, &transportErr{fmt.Errorf("cinc: bookshelf %s: %w", req.Method, err)} } - defer resp.Body.Close() + defer func() { + // Drain what a handler left unread (it may stop early on a + // checksum mismatch), so the connection can be reused. + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) + resp.Body.Close() + }() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, _ := io.ReadAll(resp.Body) - return resp.StatusCode, resp.Header, newErrorResponse(req.Method, redactQuery(req.URL), resp.StatusCode, body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + er := newErrorResponse(req.Method, redactQuery(req.URL), resp.StatusCode, nil) + er.Messages = transferErrorMessages(body) + return resp.StatusCode, resp.Header, er } return resp.StatusCode, resp.Header, handle(resp) } +// s3ErrorRE picks the Code and Message out of an S3 (or bookshelf) XML error. +var s3ErrorRE = regexp.MustCompile(`(?s)(.*?).*?(.*?)`) + +// transferErrorMessages is what an error from a pre-signed URL reports of its +// body. An S3 error can echo the request's credentials (SignatureDoesNotMatch +// includes the canonical request, the access key and the signature), so only +// its Code and Message are kept; any other body is capped like an API one. +func transferErrorMessages(body []byte) []string { + if m := s3ErrorRE.FindSubmatch(body); m != nil { + return []string{string(m[1]) + ": " + string(m[2])} + } + if s := strings.TrimSpace(string(body)); s != "" { + return []string{truncate(s, maxRawErrorBody)} + } + return nil +} + // redactQuery returns u without its query string, which for a pre-signed // bookshelf or S3 URL carries the signature and credentials. func redactQuery(u *url.URL) string { @@ -360,6 +403,12 @@ func do[T any](ctx context.Context, c *Client, method, path string, body any) (T if err != nil { return zero, resp, err } + // Every Chef GET answers with a JSON document. An empty or null one + // (from a misbehaving proxy or cache) would otherwise decode as an empty + // object, which a read-modify-write would then write back. + if method == http.MethodGet && (len(bytes.TrimSpace(data)) == 0 || string(bytes.TrimSpace(data)) == "null") { + return zero, resp, fmt.Errorf("cinc: GET %s: empty response body", path) + } var out T if len(data) > 0 { if err := json.Unmarshal(data, &out); err != nil {