From 00b2f19c3d2e2ae1bba1a272645dec6cfabc7860 Mon Sep 17 00:00:00 2001 From: Michael Eischer <9106997+MichaelEischer@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:48:52 +0100 Subject: [PATCH] repository: enforce limits for small file types (#22213) --- internal/repository/raw.go | 60 ++++++++++++++++++++++++++-- internal/repository/raw_test.go | 71 +++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 3 deletions(-) diff --git a/internal/repository/raw.go b/internal/repository/raw.go index fc6726f39..78d704fe0 100644 --- a/internal/repository/raw.go +++ b/internal/repository/raw.go @@ -6,7 +6,9 @@ import ( "fmt" "io" + "github.com/cenkalti/backoff/v4" "github.com/restic/restic/internal/backend" + "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/restic" ) @@ -42,15 +44,67 @@ func (r *Repository) LoadRaw(ctx context.Context, t restic.FileType, id restic.I return buf, nil } +// capBuffer stores at most `remain` bytes. We can't use io.LimitReader as it would hide WriteTo, +// which is required for performance reasons on some backends. +type capBuffer struct { + buf bytes.Buffer + remain int +} + +func (c *capBuffer) Write(p []byte) (int, error) { + if len(p) > c.remain { + n, _ := c.buf.Write(p[:c.remain]) + c.remain -= n + return n, errors.New("file exceeds maximum size") + } + n, _ := c.buf.Write(p) + c.remain -= n + return n, nil +} + func loadRaw(ctx context.Context, be backend.Backend, h backend.Handle) (buf []byte, err error) { + limit := smallFileSizeLimit(h.Type) + // limit cannot be passed directly to `be.Load` as that would reject a shorter file. + // Instead, bound the copy operation. err = be.Load(ctx, h, 0, 0, func(rd io.Reader) error { - wr := new(bytes.Buffer) + if limit == 0 { + wr := new(bytes.Buffer) + if _, cerr := io.Copy(wr, rd); cerr != nil { + return cerr + } + buf = wr.Bytes() + return nil + } + + wr := &capBuffer{remain: limit + 1} _, cerr := io.Copy(wr, rd) + if wr.buf.Len() > limit { + return backoff.Permanent(errors.Errorf("%s file exceeds maximum size of %d bytes", h.Type, limit)) + } if cerr != nil { return cerr } - buf = wr.Bytes() - return cerr + buf = wr.buf.Bytes() + return nil }) return buf, err } + +func smallFileSizeLimit(t backend.FileType) int { + switch t { + case backend.KeyFile, backend.LockFile, backend.ConfigFile: + // Files are expected to be a few kilobytes. Use a generous limit of 1MB. + return 1 << 20 + case backend.IndexFile: + // In the worst case, a JSON encoded index entry can require nearly 256bytes (one blob per pack). + // An index is split after reaching 50000 blobs. As a pack file is always stored in full, account + // for the maximum (16MB pack header size limit, 37 bytes per uncompressed blob). Historically, + // compressed indexes could contain more blobs, but as we work with compressed bytes here, this + // is already accounted for. This results in the following generous overapproximation: + // 256 * (50*1000 + 16*1024*1024/37) ~= 123MB + return 128 * (1 << 20) + default: + // Snapshots currently have no size limit as they can include arbitrary amounts of exclude paths. + return 0 + } +} diff --git a/internal/repository/raw_test.go b/internal/repository/raw_test.go index 30df82d0f..2219ceff7 100644 --- a/internal/repository/raw_test.go +++ b/internal/repository/raw_test.go @@ -47,6 +47,77 @@ func TestLoadRaw(t *testing.T) { } } +func TestLoadRawLimitsSmallFiles(t *testing.T) { + over := rtest.Random(1, MiB+1) + exact := over[:MiB] + + cases := []struct { + name string + tpe restic.FileType + data []byte + ok bool + }{ + {"key at limit", restic.KeyFile, exact, true}, + {"key over limit", restic.KeyFile, over, false}, + {"lock over limit", restic.LockFile, over, false}, + {"config over limit", restic.ConfigFile, over, false}, + {"snapshot over limit", restic.SnapshotFile, over, true}, + // only check that 1MB indexes are loaded, the full limit would slow down tests + {"index over limit", restic.IndexFile, over, true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + b := mem.New() + repo, err := repository.New(b, repository.Options{}) + rtest.OK(t, err) + + id := restic.Hash(tc.data) + h := backend.Handle{Type: backend.FileType(tc.tpe), Name: id.String()} + rtest.OK(t, b.Save(context.TODO(), h, backend.NewByteReader(tc.data, b.Hasher()))) + + buf, err := repo.LoadRaw(context.TODO(), tc.tpe, id) + if tc.ok { + rtest.OK(t, err) + rtest.Assert(t, bytes.Equal(buf, tc.data), "wrong data returned for %s", tc.tpe) + return + } + rtest.Assert(t, err != nil && bytes.Contains([]byte(err.Error()), []byte("exceeds maximum size")), + "expected a size limit error for %s, got %v", tc.tpe, err) + rtest.Assert(t, buf == nil, "oversized %s returned %d bytes", tc.tpe, len(buf)) + }) + } +} + +type writeToOnly struct { + rd io.Reader +} + +func (r *writeToOnly) Read([]byte) (int, error) { + return 0, errors.New("should have called WriteTo") +} + +func (r *writeToOnly) WriteTo(w io.Writer) (int64, error) { + return io.Copy(w, r.rd) +} + +func (r *writeToOnly) Close() error { return nil } + +func TestLoadRawUsesWriteTo(t *testing.T) { + data := []byte("key file") + id := restic.Hash(data) + b := mock.NewBackend() + b.OpenReaderFn = func(ctx context.Context, h backend.Handle, length int, offset int64) (io.ReadCloser, error) { + return &writeToOnly{rd: bytes.NewReader(data)}, nil + } + repo, err := repository.New(b, repository.Options{}) + rtest.OK(t, err) + + buf, err := repo.LoadRaw(context.TODO(), restic.KeyFile, id) + rtest.OK(t, err) + rtest.Equals(t, data, buf) +} + func TestLoadRawBroken(t *testing.T) { b := mock.NewBackend() repo, err := repository.New(b, repository.Options{})