Complete safety and transfer remediation verification

This commit is contained in:
2026-12-01 20:47:59 +00:00
parent f59a53e31b
commit 75eddf8adc
27 changed files with 309 additions and 328 deletions

View File

@@ -2,22 +2,106 @@ package storage
import (
"context"
"errors"
"fmt"
"io"
)
// WriterDownloader is implemented by storage backends that stream an object
// into a caller-owned file handle.
type WriterDownloader interface {
DownloadTo(ctx context.Context, key string, destination io.Writer) error
// StreamObject copies one response into a caller-owned destination and closes
// its body. A non-nil expected size is authoritative; otherwise the response's
// known size bounds the transfer. Unknown response sizes stream to EOF.
func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) {
label := func(size *int64) string {
if size != nil {
return fmt.Sprintf("download object %q (expected %d bytes)", key, *size)
}
return fmt.Sprintf("download object %q", key)
}
if store == nil || destination == nil {
return info, fmt.Errorf("download object %q: store and destination are required", key)
}
if expected != nil && *expected < 0 {
return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected)
}
if err := context.Cause(ctx); err != nil {
return info, fmt.Errorf("%s: %w", label(expected), err)
}
info, body, readErr := store.Read(ctx, key)
sizeKnown := info.SizeKnown || info.Size > 0
size := expected
if size == nil && sizeKnown {
size = &info.Size
}
if body != nil {
defer func() {
if closeErr := body.Close(); closeErr != nil {
err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr))
}
}()
}
if readErr != nil {
return info, fmt.Errorf("%s: %w", label(size), readErr)
}
if body == nil {
return info, fmt.Errorf("%s: response body is missing", label(size))
}
if expected != nil && sizeKnown && info.Size != *expected {
return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size)
}
source := contextReader{ctx: ctx, reader: body}
tracked := &transferReader{reader: source}
if size == nil {
_, copyErr := io.Copy(destination, tracked)
if tracked.err != nil && !errors.Is(tracked.err, io.EOF) {
copyErr = errors.Join(copyErr, tracked.err)
}
if err := errors.Join(copyErr, context.Cause(ctx)); err != nil {
return info, fmt.Errorf("download object %q: copy body: %w", key, err)
}
return info, nil
}
count, copyErr := io.CopyN(destination, tracked, *size)
if tracked.err != nil && !errors.Is(tracked.err, io.EOF) {
copyErr = errors.Join(copyErr, tracked.err)
}
copyErr = errors.Join(copyErr, context.Cause(ctx))
if copyErr != nil {
if errors.Is(copyErr, io.EOF) && context.Cause(ctx) == nil {
return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF)
}
return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr)
}
var probe [1]byte
var n int
var probeErr error
for n == 0 && probeErr == nil {
n, probeErr = source.Read(probe[:])
}
if n > 0 {
oversized := fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size)
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
return info, errors.Join(oversized, probeErr, context.Cause(ctx))
}
return info, errors.Join(oversized, context.Cause(ctx))
}
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, errors.Join(probeErr, context.Cause(ctx)))
}
if err := context.Cause(ctx); err != nil {
return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err)
}
return info, nil
}
// DownloadTo streams one object into destination. Destination-confined callers
// require this capability rather than granting a backend a mutable pathname.
func DownloadTo(ctx context.Context, store ObjectStore, key string, destination io.Writer) error {
writer, ok := store.(WriterDownloader)
if !ok {
return fmt.Errorf("object store does not support handle-confined downloads")
}
return writer.DownloadTo(ctx, key, destination)
type transferReader struct {
reader io.Reader
err error
}
func (r *transferReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
if err != nil {
r.err = err
}
return n, err
}

View File

@@ -8,7 +8,6 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"sync"
@@ -21,19 +20,17 @@ type FakeBackend struct {
Objects map[string]FakeObject
Uploads []FakeUploadCall
Downloads []FakeDownloadCall
Reads []FakeReadCall
Deletes []string
ExistsKeys []string
ListErr error
DownloadErr error
UploadErr error
DeleteErr error
ExistsErr error
UploadHook func(FakeUploadCall) error
DownloadHook func(FakeDownloadCall) error
ReadHook func(FakeReadCall) error
ListErr error
ReadErr error
UploadErr error
DeleteErr error
ExistsErr error
UploadHook func(FakeUploadCall) error
ReadHook func(FakeReadCall) error
}
// FakeUploadCall captures one upload invocation in call order.
@@ -43,13 +40,6 @@ type FakeUploadCall struct {
Options UploadOptions
}
// FakeDownloadCall captures one download invocation in call order.
type FakeDownloadCall struct {
Key string
LocalPath string
Bytes int64
}
// FakeReadCall captures one opened object in call order.
type FakeReadCall struct {
Key string
@@ -123,8 +113,8 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read
if err := ctx.Err(); err != nil {
return ObjectInfo{}, nil, err
}
if f.DownloadErr != nil {
return ObjectInfo{}, nil, f.DownloadErr
if f.ReadErr != nil {
return ObjectInfo{}, nil, f.ReadErr
}
normalizedKey := normalizeObjectKey(key)
if f.ReadHook != nil {
@@ -148,54 +138,6 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read
return ObjectInfo{Key: obj.Key, Size: int64(len(obj.Data)), SizeKnown: true, ETag: obj.ETag, LastModified: obj.LastModified}, io.NopCloser(bytes.NewReader(obj.Data)), nil
}
// DownloadTo writes one object to a caller-owned destination writer.
func (f *FakeBackend) DownloadTo(ctx context.Context, key string, destination io.Writer) error {
if err := ctx.Err(); err != nil {
return err
}
if f.DownloadErr != nil {
return f.DownloadErr
}
if destination == nil {
return fmt.Errorf("download object: destination writer is required")
}
if f.DownloadHook != nil {
if err := f.DownloadHook(FakeDownloadCall{Key: normalizeObjectKey(key)}); err != nil {
return err
}
}
_, source, err := f.Read(ctx, key)
if err != nil {
return err
}
defer source.Close()
count, err := io.Copy(destination, source)
if err != nil {
return fmt.Errorf("download object %q: write destination: %w", key, err)
}
f.mu.Lock()
f.Downloads = append(f.Downloads, FakeDownloadCall{Key: normalizeObjectKey(key), Bytes: count})
f.mu.Unlock()
return nil
}
// Download writes one object to a local path.
func (f *FakeBackend) Download(ctx context.Context, key, localPath string) error {
if strings.TrimSpace(localPath) == "" {
return fmt.Errorf("download object: local path is required")
}
if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil {
return fmt.Errorf("download object %q: create parent directory: %w", key, err)
}
destination, err := os.Create(localPath)
if err != nil {
return fmt.Errorf("download object %q: create local file: %w", key, err)
}
defer destination.Close()
return f.DownloadTo(ctx, key, destination)
}
// Upload reads a local file and stores it under key.
func (f *FakeBackend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) {
if err := ctx.Err(); err != nil {

View File

@@ -27,23 +27,6 @@ func TestFakeBackendListPrefixFiltering(t *testing.T) {
}
}
func TestFakeBackendDownload(t *testing.T) {
fake := &FakeBackend{}
fake.SeedObject(FakeObject{Key: "audio/a.flac", Data: []byte("audio-a")})
dst := filepath.Join(t.TempDir(), "nested", "a.flac")
if err := fake.Download(context.Background(), `audio\a.flac`, dst); err != nil {
t.Fatalf("Download() error = %v", err)
}
data, err := os.ReadFile(dst)
if err != nil {
t.Fatalf("ReadFile() error = %v", err)
}
if string(data) != "audio-a" {
t.Fatalf("downloaded content = %q, want %q", string(data), "audio-a")
}
}
func TestFakeBackendUploadAndExists(t *testing.T) {
fake := &FakeBackend{}
@@ -119,13 +102,13 @@ func TestFakeBackendConditionalUploadRejectsStaleGeneration(t *testing.T) {
}
func TestFakeBackendObjectErrors(t *testing.T) {
fake := &FakeBackend{DownloadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")}
fake := &FakeBackend{ReadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")}
if _, err := fake.List(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "list fail") {
t.Fatalf("List() error = %v, want list fail", err)
}
if err := fake.Download(context.Background(), "x", filepath.Join(t.TempDir(), "x")); err == nil || !strings.Contains(err.Error(), "download fail") {
t.Fatalf("Download() error = %v, want download fail", err)
if _, _, err := fake.Read(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "download fail") {
t.Fatalf("Read() error = %v, want read failure", err)
}
local := filepath.Join(t.TempDir(), "x.txt")
_ = os.WriteFile(local, []byte("x"), 0o644)

View File

@@ -25,7 +25,6 @@ type ReaderUploader interface {
type ObjectStore interface {
List(ctx context.Context, prefix string) ([]ObjectInfo, error)
Read(ctx context.Context, key string) (ObjectInfo, io.ReadCloser, error)
Download(ctx context.Context, key, localPath string) error
Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error)
UploadConditional(ctx context.Context, source io.Reader, key string, opts UploadOptions, condition WriteCondition) (ObjectInfo, error)
Delete(ctx context.Context, key string) error

View File

@@ -6,7 +6,6 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
@@ -175,45 +174,6 @@ func (b *S3Backend) Read(ctx context.Context, key string) (ObjectInfo, io.ReadCl
}, resp.Body, nil
}
// DownloadTo retrieves one object into the caller-owned destination writer.
func (b *S3Backend) DownloadTo(ctx context.Context, key string, destination io.Writer) error {
if destination == nil {
return fmt.Errorf("download object: destination writer is required")
}
_, body, err := b.Read(ctx, key)
if err != nil {
return fmt.Errorf("download object %q: %w", normalizeObjectKey(key), err)
}
defer body.Close()
if _, err := io.Copy(destination, body); err != nil {
return fmt.Errorf("download object %q: copy body: %w", normalizeObjectKey(key), err)
}
return nil
}
// Download retrieves one object to localPath, creating parent directories as needed.
func (b *S3Backend) Download(ctx context.Context, key, localPath string) error {
if strings.TrimSpace(localPath) == "" {
return fmt.Errorf("download object: local path is required")
}
if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil {
return fmt.Errorf("download object %q: create parent directory: %w", key, err)
}
dst, err := os.Create(localPath)
if err != nil {
return fmt.Errorf("download object %q: create local file: %w", key, err)
}
defer dst.Close()
if err := b.DownloadTo(ctx, key, dst); err != nil {
return err
}
if err := dst.Sync(); err != nil {
return fmt.Errorf("download object %q: sync local file: %w", key, err)
}
return nil
}
// Upload sends a local file to key.
func (b *S3Backend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) {
normalizedKey := normalizeObjectKey(key)

View File

@@ -171,27 +171,6 @@ func TestS3BackendListAndKeyNormalization(t *testing.T) {
}
}
func TestS3BackendDownloadCreatesParentDirectory(t *testing.T) {
client := &fakeS3API{getBody: io.NopCloser(strings.NewReader("audio"))}
backend := &S3Backend{bucket: "bucket-1", client: client}
dst := filepath.Join(t.TempDir(), "nested", "clip.flac")
if err := backend.Download(context.Background(), `audio\clip.flac`, dst); err != nil {
t.Fatalf("Download() error = %v", err)
}
data, err := os.ReadFile(dst)
if err != nil {
t.Fatalf("ReadFile() error = %v", err)
}
if string(data) != "audio" {
t.Fatalf("downloaded content = %q, want %q", string(data), "audio")
}
if client.lastGet == nil || *client.lastGet.Key != "audio/clip.flac" {
t.Fatalf("GetObject key = %#v, want normalized key", client.lastGet)
}
}
func TestS3BackendReadReturnsOpenedObjectMetadata(t *testing.T) {
lastModified := time.Date(2026, 8, 11, 1, 2, 3, 0, time.UTC)
client := &fakeS3API{

View File

@@ -1,78 +0,0 @@
package storage
import (
"context"
"errors"
"fmt"
"io"
)
// StreamObject copies one response into a caller-owned destination and closes
// its body. A non-nil expected size is authoritative; otherwise the response's
// known size bounds the transfer. Unknown response sizes stream to EOF.
func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) {
label := func(size *int64) string {
if size != nil {
return fmt.Sprintf("download object %q (expected %d bytes)", key, *size)
}
return fmt.Sprintf("download object %q", key)
}
if store == nil || destination == nil {
return info, fmt.Errorf("download object %q: store and destination are required", key)
}
if expected != nil && *expected < 0 {
return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected)
}
if err := ctx.Err(); err != nil {
return info, fmt.Errorf("%s: %w", label(expected), err)
}
info, body, err := store.Read(ctx, key)
if err != nil {
return info, fmt.Errorf("%s: %w", label(expected), err)
}
if body == nil {
return info, fmt.Errorf("%s: response body is missing", label(expected))
}
sizeKnown := info.SizeKnown || info.Size > 0
size := expected
if size == nil && sizeKnown {
size = &info.Size
}
defer func() {
if closeErr := body.Close(); closeErr != nil {
err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr))
}
}()
if expected != nil && sizeKnown && info.Size != *expected {
return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size)
}
source := contextReader{ctx: ctx, reader: body}
if size == nil {
if _, err := io.Copy(destination, source); err != nil {
return info, fmt.Errorf("download object %q: copy body: %w", key, err)
}
if err := ctx.Err(); err != nil {
return info, fmt.Errorf("download object %q: %w", key, err)
}
return info, nil
}
count, copyErr := io.CopyN(destination, source, *size)
if copyErr != nil {
if errors.Is(copyErr, io.EOF) {
return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF)
}
return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr)
}
var probe [1]byte
n, probeErr := io.ReadFull(source, probe[:])
if n > 0 {
return info, fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size)
}
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, probeErr)
}
if err := ctx.Err(); err != nil {
return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err)
}
return info, nil
}

View File

@@ -76,3 +76,39 @@ func TestStreamObjectPreservesFailuresAndClosesResponse(t *testing.T) {
})
}
}
type byteAndErrorReader struct{ err error }
func (r byteAndErrorReader) Read(p []byte) (int, error) { p[0] = 'x'; return 1, r.err }
func TestStreamObjectPreservesProbeAndOpenErrors(t *testing.T) {
failure := errors.New("synthetic read error")
closeErr := errors.New("synthetic close error")
body := &trackingReadCloser{reader: byteAndErrorReader{failure}, closeErr: closeErr}
store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) {
return ObjectInfo{SizeKnown: true}, body, nil
}}
_, err := StreamObject(context.Background(), store, "key", io.Discard, nil)
if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed {
t.Fatalf("probe error=%v closed=%v", err, body.closed)
}
body = &trackingReadCloser{reader: strings.NewReader(""), closeErr: closeErr}
store.read = func(context.Context, string) (ObjectInfo, io.ReadCloser, error) { return ObjectInfo{}, body, failure }
_, err = StreamObject(context.Background(), store, "key", io.Discard, nil)
if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed {
t.Fatalf("open error=%v closed=%v", err, body.closed)
}
}
func TestStreamObjectPreservesCancellationCause(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
cause := errors.New("synthetic cancellation cause")
body := &trackingReadCloser{reader: strings.NewReader("abc"), chunkSize: 1, afterRead: func() { cancel(cause) }}
store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) {
return ObjectInfo{Size: 3, SizeKnown: true}, body, nil
}}
_, err := StreamObject(ctx, store, "key", io.Discard, nil)
if !errors.Is(err, cause) || !body.closed {
t.Fatalf("error=%v closed=%v", err, body.closed)
}
}

View File

@@ -32,7 +32,7 @@ func TestDownloadObjectToTempSuccess(t *testing.T) {
func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) {
sentinel := errors.New("download failed")
store := &FakeBackend{DownloadErr: sentinel}
store := &FakeBackend{ReadErr: sentinel}
pattern := "narratio-test-fail-*.txt"
before, err := filepath.Glob(filepath.Join(os.TempDir(), "narratio-test-fail-*.txt"))
if err != nil {
@@ -57,7 +57,7 @@ func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) {
func TestDownloadObjectToTempCallerContextWrappingPreservesCause(t *testing.T) {
sentinel := errors.New("object missing")
store := &FakeBackend{DownloadErr: sentinel}
store := &FakeBackend{ReadErr: sentinel}
_, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt", nil)
if err == nil {