Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(attachments): support HTTP Range resume on proxy download (MUL-3962)

n37430d3aca600ae
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 42cfc65d44..c039a317de 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -9,6 +9,7 @@ import (
"net/netip"
"net/url"
"path"
+ "strconv"
"strings"
"time"
@@ -740,6 +741,22 @@ func (h *Handler) ServeLocalUpload(w http.ResponseWriter, r *http.Request) {
local.ServeFile(w, r, key)
}
+// proxyAttachmentDownload streams an attachment through the API instead of
+// redirecting to a signed storage URL (used for local-disk / private-host
+// backends, see resolveAttachmentDownloadMode).
+//
+// It supports HTTP Range requests so a download interrupted mid-stream can be
+// resumed with `Range: bytes=<resume>-` instead of restarting from byte 0
+// (RAS-29). Two paths:
+//
+// - Seekable backend (local disk returns *os.File): delegate to
+// http.ServeContent, which implements Range / If-Range / 206 /
+// Content-Range / 416 correctly out of the box.
+// - Non-seekable backend (S3/MinIO streaming body): advertise
+// Accept-Ranges and implement single-range requests by hand
+// (serveProxyRange). Multi-range is not implemented on this path; per
+// RFC 7233 it is ignored and the full body is served (200), matching the
+// seekable path's successful outcome rather than failing with 416.
func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request, att db.Attachment, key string) {
reader, err := h.Storage.GetReader(r.Context(), key)
if err != nil {
@@ -754,16 +771,219 @@ func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
- if att.SizeBytes >= 0 {
- w.Header().Set("Content-Length", fmt.Sprintf("%d", att.SizeBytes))
- }
w.Header().Set("Content-Disposition", storage.ContentDisposition(att.ContentType, att.Filename))
+ // no-store predates Range support; keep it. Range/206 semantics are
+ // independent of caching — clients resume via Content-Range, not the cache.
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
h.setAttachmentPreviewSecurityHeaders(w)
- if _, err := io.Copy(w, reader); err != nil {
- slog.Error("failed to stream attachment download", "id", uuidToString(att.ID), "error", err)
+
+ // Seekable backends get full standard-library Range handling. A zero
+ // modTime disables Last-Modified / If-Modified-Since (we keep no-store);
+ // ServeContent still honors Range and sets Accept-Ranges / Content-Length /
+ // Content-Range / status itself, and respects the headers we set above.
+ if seeker, ok := reader.(io.ReadSeeker); ok {
+ http.ServeContent(w, r, att.Filename, time.Time{}, seeker)
+ return
+ }
+
+ // Non-seekable backend: single-range fallback.
+ h.serveProxyRange(w, r, att, reader)
+}
+
+// serveProxyRange streams a (possibly partial) attachment body from a
+// forward-only reader. It always advertises Accept-Ranges: bytes and, when the
+// request carries a satisfiable single-range `Range` header, replies 206 +
+// Content-Range with just that byte interval. Without a Range header (or when
+// the size is unknown) it streams the whole body as a 200, preserving the
+// pre-RAS-29 behavior. An unsatisfiable range yields 416 + `Content-Range:
+// bytes */<total>` per RFC 7233.
+func (h *Handler) serveProxyRange(w http.ResponseWriter, r *http.Request, att db.Attachment, reader io.Reader) {
+ total := att.SizeBytes
+ w.Header().Set("Accept-Ranges", "bytes")
+
+ rangeHeader := strings.TrimSpace(r.Header.Get("Range"))
+
+ // Decide how to respond. We serve the full body (200) when there is no Range,
+ // when the total size is unknown (total < 0), or when parseSingleByteRange
+ // classifies the Range as unsupported — multi-range, or a well-formed range
+ // against an empty object (see rangeUnsupported). A well-formed, in-bounds
+ // single range yields 206; a well-formed but out-of-bounds range on a
+ // non-empty object is the only case that yields 416.
+ serveFull := rangeHeader == "" || total < 0
+ var start, length int64
+ if !serveFull {
+ var outcome rangeParseOutcome
+ start, length, outcome = parseSingleByteRange(rangeHeader, total)
+ switch outcome {
+ case rangeUnsupported:
+ // Unsupported Range form (multi-range). RFC 7233 requires an
+ // unsupported Range to be *ignored* and the full representation served
+ // (200), not rejected with 416. This also keeps the non-seekable path
+ // from diverging from the seekable http.ServeContent path, which
+ // answers multi-range with a successful 206 multipart: both backends
+ // now return complete, correctly-labeled data instead of one silently
+ // turning a resumable download into a hard 416 failure.
+ serveFull = true
+ case rangeUnsatisfiable:
+ // Well-formed bytes range that does not overlap the content. RFC 7233
+ // §4.4 requires the total in the Content-Range of a 416 response.
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", total))
+ writeError(w, http.StatusRequestedRangeNotSatisfiable, "requested range not satisfiable")
+ return
+ }
+ }
+
+ if serveFull {
+ if total >= 0 {
+ w.Header().Set("Content-Length", strconv.FormatInt(total, 10))
+ }
+ if _, err := io.Copy(w, reader); err != nil {
+ slog.Error("failed to stream attachment download", "id", uuidToString(att.ID), "error", err)
+ }
+ return
+ }
+
+ // Satisfiable single range → 206. Forward-only reader: discard the bytes
+ // before `start` before copying the requested interval. Wasteful for large
+ // offsets but correct; seekable backends never reach here (they take the
+ // ServeContent path above).
+ if start > 0 {
+ if _, err := io.CopyN(io.Discard, reader, start); err != nil {
+ // The skip failed BEFORE any response header was written. We must send
+ // an explicit error status here: a bare `return` would let net/http
+ // emit its default 200 OK + empty body, which a resuming client reads
+ // as "Range ignored, here is the whole file" — silently turning a
+ // transient storage read error into a corrupt/empty download and
+ // defeating the very resume feature this path implements. (A copy
+ // failure AFTER WriteHeader below can only be logged: the 206 status
+ // is already on the wire and cannot be revised.)
+ slog.Error("failed to skip to range start for attachment", "id", uuidToString(att.ID), "error", err)
+ writeError(w, http.StatusBadGateway, "failed to read attachment range")
+ return
+ }
+ }
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, start+length-1, total))
+ w.Header().Set("Content-Length", strconv.FormatInt(length, 10))
+ w.WriteHeader(http.StatusPartialContent)
+ if _, err := io.CopyN(w, reader, length); err != nil {
+ slog.Error("failed to stream attachment range", "id", uuidToString(att.ID), "error", err)
+ }
+}
+
+// rangeParseOutcome classifies how serveProxyRange must respond to a `Range`
+// header on the forward-only (non-seekable) proxy path. It exists so the three
+// distinct HTTP outcomes required by RFC 7233 are not collapsed into a single
+// bool — collapsing them is exactly what caused a multi-range request to fail
+// with 416 on this path while succeeding (206 multipart) on the seekable path.
+type rangeParseOutcome int
+
+const (
+ // rangeSatisfiable: a single byte range we can serve as 206 + Content-Range.
+ rangeSatisfiable rangeParseOutcome = iota
+ // rangeUnsatisfiable: a well-formed request that cannot be served as a range
+ // we support — a bytes range that does not overlap the content (start at/after
+ // EOF, reversed), or a malformed / unknown-unit Range. stdlib http.ServeContent
+ // answers all of these with 416, so replying 416 here keeps the two backends
+ // aligned; the caller adds `Content-Range: bytes */<total>` (RFC 7233 §4.4).
+ rangeUnsatisfiable
+ // rangeUnsupported: a well-formed Range this path answers by ignoring the
+ // Range and serving the full body (200), per RFC 7233. Two cases:
+ // - multi-range (`bytes=a-b,c-d`): the seekable path serves it as a 206
+ // multipart, so a full 200 here keeps both paths returning complete data
+ // instead of one hard-failing with 416.
+ // - a well-formed byte range against an EMPTY object (size == 0): there are
+ // no bytes to satisfy any range, and stdlib http.ServeContent ignores the
+ // Range and returns an empty 200 rather than 416. Classifying it here as
+ // unsupported (→ empty 200) keeps the non-seekable path aligned with the
+ // seekable one; answering 416 would make the same request against a
+ // 0-byte attachment succeed on a seekable backend but fail on an
+ // S3/MinIO stream. Genuinely malformed / unknown-unit ranges against an
+ // empty object stay rangeUnsatisfiable (416), matching ServeContent.
+ rangeUnsupported
+)
+
+// parseSingleByteRange parses a single-range HTTP `Range` header value against
+// a known content size and returns the absolute start offset, byte length, and
+// an outcome telling the caller which status to send (see rangeParseOutcome).
+// start/length are only meaningful when the outcome is rangeSatisfiable.
+//
+// Supported forms (RFC 7233): `bytes=start-end`, `bytes=start-` (to EOF), and
+// `bytes=-suffix` (final suffix bytes). An out-of-range end is clamped to the
+// last byte; a start at or past EOF on a non-empty object is unsatisfiable (416).
+// Multi-range, and any well-formed range against an empty object (size == 0),
+// are valid-but-unsupported forms and yield rangeUnsupported (ignored → full
+// body), matching how the seekable http.ServeContent path handles them.
+func parseSingleByteRange(header string, size int64) (start, length int64, outcome rangeParseOutcome) {
+ const prefix = "bytes="
+ if !strings.HasPrefix(header, prefix) {
+ // Unknown / missing unit (e.g. "items=0-10", "0-100"). stdlib
+ // http.ServeContent rejects these with 416; mirror that here.
+ return 0, 0, rangeUnsatisfiable
+ }
+ spec := strings.TrimSpace(header[len(prefix):])
+ if spec == "" {
+ return 0, 0, rangeUnsatisfiable
+ }
+ // Multi-range is a valid HTTP form we do not implement on this forward-only
+ // path; ignore it and serve the full body rather than failing with 416.
+ if strings.Contains(spec, ",") {
+ return 0, 0, rangeUnsupported
+ }
+ dash := strings.IndexByte(spec, '-')
+ if dash < 0 {
+ return 0, 0, rangeUnsatisfiable
+ }
+ startStr := strings.TrimSpace(spec[:dash])
+ endStr := strings.TrimSpace(spec[dash+1:])
+
+ if startStr == "" {
+ // Suffix form: bytes=-N → final N bytes.
+ if endStr == "" {
+ return 0, 0, rangeUnsatisfiable
+ }
+ n, err := strconv.ParseInt(endStr, 10, 64)
+ if err != nil || n <= 0 {
+ return 0, 0, rangeUnsatisfiable
+ }
+ if size == 0 {
+ // Well-formed suffix against an empty object: no bytes to satisfy it.
+ // Ignore the Range and serve an empty 200 (rangeUnsupported) to match
+ // the seekable path, instead of a divergent 416.
+ return 0, 0, rangeUnsupported
+ }
+ if n > size {
+ n = size
+ }
+ return size - n, n, rangeSatisfiable
+ }
+
+ s, err := strconv.ParseInt(startStr, 10, 64)
+ if err != nil || s < 0 {
+ return 0, 0, rangeUnsatisfiable
+ }
+ if s >= size {
+ // The start is at or beyond EOF, so no bytes overlap. For an empty object
+ // (size == 0) every start is at EOF; stdlib http.ServeContent ignores the
+ // Range and serves an empty 200 there (it never validates the end once the
+ // start is out of range), so classify as rangeUnsupported (→ empty 200) to
+ // stay aligned. For a non-empty object a start past EOF is a genuine 416.
+ if size == 0 {
+ return 0, 0, rangeUnsupported
+ }
+ return 0, 0, rangeUnsatisfiable
+ }
+ if endStr == "" {
+ return s, size - s, rangeSatisfiable
+ }
+ e, err := strconv.ParseInt(endStr, 10, 64)
+ if err != nil || e < s {
+ return 0, 0, rangeUnsatisfiable
+ }
+ if e >= size {
+ e = size - 1
}
+ return s, e - s + 1, rangeSatisfiable
}
func (h *Handler) setAttachmentPreviewSecurityHeaders(w http.ResponseWriter) {
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 9714048b25..66b1ce73d2 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -138,6 +138,67 @@ func (m *mockStorage) put(key string, data []byte) {
m.files[key] = append([]byte(nil), data...)
}
+// seekableReadCloser adapts a *bytes.Reader (which is an io.ReadSeeker) into an
+// io.ReadCloser, mirroring what LocalStorage.GetReader returns (an *os.File is
+// seekable). Used to exercise proxyAttachmentDownload's http.ServeContent path.
+type seekableReadCloser struct{ *bytes.Reader }
+
+func (seekableReadCloser) Close() error { return nil }
+
+// seekableMockStorage is a mockStorage whose GetReader returns a seekable body,
+// so proxyAttachmentDownload takes the http.ServeContent branch (the local-disk
+// shape) instead of the manual single-range fallback.
+type seekableMockStorage struct{ mockStorage }
+
+func (m *seekableMockStorage) GetReader(_ context.Context, key string) (io.ReadCloser, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if data, ok := m.files[key]; ok {
+ return seekableReadCloser{bytes.NewReader(data)}, nil
+ }
+ return nil, fmt.Errorf("seekableMockStorage GetReader: key not found: %q", key)
+}
+
+// failingReader serves up to failAfter bytes and then errors on the next Read.
+// It is forward-only (no Seek), so proxyAttachmentDownload routes it through the
+// manual serveProxyRange path — letting us simulate a storage backend that dies
+// mid-stream while the handler is discarding bytes to reach a Range start.
+type failingReader struct {
+ data []byte
+ pos int
+ failAfter int
+}
+
+func (f *failingReader) Read(p []byte) (int, error) {
+ if f.pos >= f.failAfter {
+ return 0, fmt.Errorf("simulated storage read failure at offset %d", f.pos)
+ }
+ if remaining := f.failAfter - f.pos; len(p) > remaining {
+ p = p[:remaining]
+ }
+ n := copy(p, f.data[f.pos:])
+ f.pos += n
+ return n, nil
+}
+
+func (f *failingReader) Close() error { return nil }
+
+// failingMockStorage returns a failingReader so the non-seekable Range path hits
+// a read error partway through the skip-to-start CopyN.
+type failingMockStorage struct {
+ mockStorage
+ failAfter int
+}
+
+func (m *failingMockStorage) GetReader(_ context.Context, key string) (io.ReadCloser, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if data, ok := m.files[key]; ok {
+ return &failingReader{data: data, failAfter: m.failAfter}, nil
+ }
+ return nil, fmt.Errorf("failingMockStorage GetReader: key not found: %q", key)
+}
+
func TestUploadFileForeignWorkspace(t *testing.T) {
origStorage := testHandler.Storage
testHandler.Storage = &mockStorage{}
@@ -445,6 +506,29 @@ func newDownloadRequest(t *testing.T, attachmentID, workspaceID string) (*http.R
return req, httptest.NewRecorder()
}
+// requireAttachmentDownloadHeaders asserts the security / disposition headers
+// that proxyAttachmentDownload sets before choosing a Range branch are preserved
+// on the final response, whether it went out as a 206 (partial) or a full 200.
+// The Range/206 work must not drop Content-Type / Content-Disposition /
+// Cache-Control: no-store / X-Content-Type-Options / preview CSP — the seekable
+// (http.ServeContent) path in particular could silently clobber them.
+func requireAttachmentDownloadHeaders(t *testing.T, header http.Header, wantFilename string) {
+ t.Helper()
+ if got, want := header.Get("Content-Type"), "application/octet-stream"; got != want {
+ t.Fatalf("Content-Type = %q, want %q", got, want)
+ }
+ if got := header.Get("Content-Disposition"); got == "" || !strings.Contains(got, wantFilename) {
+ t.Fatalf("Content-Disposition = %q, want non-empty containing %q", got, wantFilename)
+ }
+ if got, want := header.Get("Cache-Control"), "no-store"; got != want {
+ t.Fatalf("Cache-Control = %q, want %q", got, want)
+ }
+ if got, want := header.Get("X-Content-Type-Options"), "nosniff"; got != want {
+ t.Fatalf("X-Content-Type-Options = %q, want %q", got, want)
+ }
+ requireAttachmentPreviewCSP(t, header)
+}
+
func requireAttachmentPreviewCSP(t *testing.T, header http.Header, extraAncestors ...string) {
t.Helper()
csp := header.Get("Content-Security-Policy")
@@ -869,6 +953,360 @@ func TestDownloadAttachment_ExplicitProxyStreamsPublicEndpoint(t *testing.T) {
}
}
+// setProxyDownloadHandler swaps the handler into forced-proxy mode with the
+// given storage backend and returns the seeded attachment id + body. It wires
+// t.Cleanup to restore the original handler fields.
+func setProxyDownloadHandler(t *testing.T, store storage.Storage, body []byte) string {
+ t.Helper()
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "proxy"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+
+ key := "downloads/range-sample.bin"
+ if putter, ok := store.(interface{ put(string, []byte) }); ok {
+ putter.put(key, body)
+ } else {
+ t.Fatalf("store %T does not support put()", store)
+ }
+ return seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "sample.bin", "application/octet-stream", int64(len(body)))
+}
+
+// rangeBody is a deterministic 4 KiB payload used by the Range tests so we can
+// assert that a partial response's bytes match the corresponding slice of the
+// full object.
+func rangeBody() []byte {
+ b := make([]byte, 4096)
+ for i := range b {
+ b[i] = byte(i % 251) // 251 is prime → no alignment with 256 boundaries
+ }
+ return b
+}
+
+// runProxyRangeMatrix exercises the three acceptance paths (Range hit, 416,
+// no-Range) against whichever storage backend is supplied, so both the
+// http.ServeContent (seekable) and manual (non-seekable) branches are covered
+// by identical assertions.
+func runProxyRangeMatrix(t *testing.T, newStore func() storage.Storage) {
+ body := rangeBody()
+
+ t.Run("RangeHitReturns206", func(t *testing.T) {
+ id := setProxyDownloadHandler(t, newStore(), body)
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=0-1023")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusPartialContent {
+ t.Fatalf("status = %d, want 206; body=%s", w.Code, w.Body.String())
+ }
+ if got, want := w.Header().Get("Accept-Ranges"), "bytes"; got != want {
+ t.Fatalf("Accept-Ranges = %q, want %q", got, want)
+ }
+ if got, want := w.Header().Get("Content-Range"), fmt.Sprintf("bytes 0-1023/%d", len(body)); got != want {
+ t.Fatalf("Content-Range = %q, want %q", got, want)
+ }
+ if got, want := w.Header().Get("Content-Length"), "1024"; got != want {
+ t.Fatalf("Content-Length = %q, want %q", got, want)
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body[:1024]) {
+ t.Fatalf("partial body mismatch: len(got)=%d, want first 1024 bytes of object", len(got))
+ }
+ requireAttachmentDownloadHeaders(t, w.Header(), "sample.bin")
+ })
+
+ t.Run("MidStreamRangeMatchesFullSlice", func(t *testing.T) {
+ id := setProxyDownloadHandler(t, newStore(), body)
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=1000-1999")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusPartialContent {
+ t.Fatalf("status = %d, want 206; body=%s", w.Code, w.Body.String())
+ }
+ if got, want := w.Header().Get("Content-Range"), fmt.Sprintf("bytes 1000-1999/%d", len(body)); got != want {
+ t.Fatalf("Content-Range = %q, want %q", got, want)
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body[1000:2000]) {
+ t.Fatalf("mid-stream range bytes do not match object[1000:2000]")
+ }
+ })
+
+ t.Run("SuffixRangeReturnsTail", func(t *testing.T) {
+ id := setProxyDownloadHandler(t, newStore(), body)
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=-500")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusPartialContent {
+ t.Fatalf("status = %d, want 206; body=%s", w.Code, w.Body.String())
+ }
+ start := len(body) - 500
+ if got, want := w.Header().Get("Content-Range"), fmt.Sprintf("bytes %d-%d/%d", start, len(body)-1, len(body)); got != want {
+ t.Fatalf("Content-Range = %q, want %q", got, want)
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body[start:]) {
+ t.Fatalf("suffix range bytes do not match object tail")
+ }
+ })
+
+ t.Run("UnsatisfiableRangeReturns416", func(t *testing.T) {
+ id := setProxyDownloadHandler(t, newStore(), body)
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", len(body)+10, len(body)+20))
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusRequestedRangeNotSatisfiable {
+ t.Fatalf("status = %d, want 416; body=%s", w.Code, w.Body.String())
+ }
+ if got, want := w.Header().Get("Content-Range"), fmt.Sprintf("bytes */%d", len(body)); got != want {
+ t.Fatalf("Content-Range = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("NoRangeReturnsFull200", func(t *testing.T) {
+ id := setProxyDownloadHandler(t, newStore(), body)
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ if got, want := w.Header().Get("Accept-Ranges"), "bytes"; got != want {
+ t.Fatalf("Accept-Ranges = %q, want %q", got, want)
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body) {
+ t.Fatalf("full body mismatch: len(got)=%d, want %d", len(got), len(body))
+ }
+ requireAttachmentDownloadHeaders(t, w.Header(), "sample.bin")
+ })
+}
+
+// TestDownloadAttachment_ProxyRange_Seekable covers the http.ServeContent path
+// taken when the storage backend returns a seekable reader (local disk).
+func TestDownloadAttachment_ProxyRange_Seekable(t *testing.T) {
+ runProxyRangeMatrix(t, func() storage.Storage { return &seekableMockStorage{} })
+}
+
+// TestDownloadAttachment_ProxyRange_NonSeekable covers the manual single-range
+// fallback taken when the backend returns a forward-only stream (S3/MinIO).
+func TestDownloadAttachment_ProxyRange_NonSeekable(t *testing.T) {
+ runProxyRangeMatrix(t, func() storage.Storage { return &mockStorage{} })
+}
+
+// TestDownloadAttachment_NonSeekableRangeSkipFailureReturns502 is the must-fix
+// regression (RAS-31 ①). When the storage read fails while the handler is
+// skipping forward to the Range start — before any response header is written —
+// it must reply with an honest 502, NOT net/http's default 200 OK + empty body.
+// A resuming client reads that default 200 as "Range ignored, this is the full
+// object", silently turning a transient storage error into a corrupt/empty
+// download and defeating the resume feature itself.
+func TestDownloadAttachment_NonSeekableRangeSkipFailureReturns502(t *testing.T) {
+ body := rangeBody()
+ // Die at offset 500, well before the Range start (1000), so the failure lands
+ // inside the skip CopyN rather than the payload copy.
+ store := &failingMockStorage{failAfter: 500}
+ id := setProxyDownloadHandler(t, store, body)
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=1000-1999")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502; body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "failed to read attachment range") {
+ t.Fatalf("502 body should carry the honest error, got %q", w.Body.String())
+ }
+ if got := w.Body.Bytes(); bytes.Contains(got, body[:64]) {
+ t.Fatalf("502 response must not leak object bytes; got %q", got)
+ }
+}
+
+// TestDownloadAttachment_NonSeekableMultiRangeServesFull200 is the should-fix
+// (RAS-31 ②). A multi-range request the non-seekable path cannot serve must be
+// ignored and answered with a full 200 (RFC 7233), not 416. Paired with the
+// seekable test below, this proves the two backends no longer disagree on
+// success vs failure for the same multi-range request.
+func TestDownloadAttachment_NonSeekableMultiRangeServesFull200(t *testing.T) {
+ body := rangeBody()
+ id := setProxyDownloadHandler(t, &mockStorage{}, body)
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=0-10,20-30")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (multi-range ignored); body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body) {
+ t.Fatalf("multi-range should serve full body: len(got)=%d, want %d", len(got), len(body))
+ }
+ if got := w.Header().Get("Content-Range"); got != "" {
+ t.Fatalf("full 200 response must not carry Content-Range, got %q", got)
+ }
+ if got, want := w.Header().Get("Accept-Ranges"), "bytes"; got != want {
+ t.Fatalf("Accept-Ranges = %q, want %q", got, want)
+ }
+ requireAttachmentDownloadHeaders(t, w.Header(), "sample.bin")
+}
+
+// TestDownloadAttachment_SeekableMultiRangeServes206 documents the other half of
+// the ②-divergence: the seekable (http.ServeContent) path answers the same
+// multi-range request with a successful 206 multipart. Together with the
+// non-seekable 200 test above, it shows neither backend fails the request with
+// 416 — the divergence the maintainer flagged is gone.
+func TestDownloadAttachment_SeekableMultiRangeServes206(t *testing.T) {
+ body := rangeBody()
+ id := setProxyDownloadHandler(t, &seekableMockStorage{}, body)
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", "bytes=0-10,20-30")
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusPartialContent {
+ t.Fatalf("status = %d, want 206 (multipart); body len=%d", w.Code, w.Body.Len())
+ }
+ if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "multipart/byteranges") {
+ t.Fatalf("Content-Type = %q, want multipart/byteranges", ct)
+ }
+}
+
+// TestDownloadAttachment_NonSeekableEmptyObjectRangeServesFull200 covers the
+// zero-length nit the maintainer flagged during re-review (same class as RAS-31
+// ②). A WELL-FORMED Range against a 0-byte attachment used to collapse to 416 on
+// the non-seekable path (parseSingleByteRange → rangeUnsatisfiable) while the
+// seekable http.ServeContent path ignores the Range and returns an empty 200.
+// parseSingleByteRange now classifies a well-formed range against an empty object
+// as rangeUnsupported (→ empty 200), so neither backend hard-fails it. Malformed
+// ranges are covered by the 416 companion test below.
+func TestDownloadAttachment_NonSeekableEmptyObjectRangeServesFull200(t *testing.T) {
+ // Both a start-based range and a suffix range must be ignored on an empty
+ // object; the suffix form ("bytes=-100" against size 0) is the exact case the
+ // maintainer referenced.
+ for _, rangeHeader := range []string{"bytes=0-", "bytes=-100", "bytes=0-99"} {
+ t.Run(rangeHeader, func(t *testing.T) {
+ id := setProxyDownloadHandler(t, &mockStorage{}, []byte{})
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", rangeHeader)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (Range ignored on empty object); body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Body.Len(); got != 0 {
+ t.Fatalf("empty object must serve an empty body, got %d bytes", got)
+ }
+ if got := w.Header().Get("Content-Length"); got != "0" {
+ t.Fatalf("Content-Length = %q, want %q for an empty 200", got, "0")
+ }
+ if got := w.Header().Get("Content-Range"); got != "" {
+ t.Fatalf("full 200 response must not carry Content-Range, got %q", got)
+ }
+ if got, want := w.Header().Get("Accept-Ranges"), "bytes"; got != want {
+ t.Fatalf("Accept-Ranges = %q, want %q", got, want)
+ }
+ requireAttachmentDownloadHeaders(t, w.Header(), "sample.bin")
+ })
+ }
+}
+
+// TestDownloadAttachment_NonSeekableEmptyObjectMalformedRangeReturns416 is the
+// guard against over-correcting the zero-length nit: a MALFORMED / unknown-unit
+// Range against a 0-byte object must still return 416, not be swallowed into a
+// 200. stdlib http.ServeContent returns 416 for these even on an empty object
+// (it rejects the range before the empty-content short-circuit), so returning
+// 200 here would introduce a NEW backend-dependent divergence — the exact
+// regression a blanket "total == 0 → 200" would cause.
+func TestDownloadAttachment_NonSeekableEmptyObjectMalformedRangeReturns416(t *testing.T) {
+ for _, rangeHeader := range []string{"items=0-10", "bytes=abc-def", "bytes=100"} {
+ t.Run(rangeHeader, func(t *testing.T) {
+ id := setProxyDownloadHandler(t, &mockStorage{}, []byte{})
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ req.Header.Set("Range", rangeHeader)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusRequestedRangeNotSatisfiable {
+ t.Fatalf("status = %d, want 416 for malformed range on empty object; body=%s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestParseSingleByteRange(t *testing.T) {
+ const size = 1000
+ tests := []struct {
+ name string
+ header string
+ size int64
+ wantOutcome rangeParseOutcome
+ wantStart int64
+ wantLength int64
+ }{
+ {"full closed range", "bytes=0-1023", 2000, rangeSatisfiable, 0, 1024},
+ {"open-ended range", "bytes=500-", size, rangeSatisfiable, 500, 500},
+ {"end clamped to eof", "bytes=900-5000", size, rangeSatisfiable, 900, 100},
+ {"suffix range", "bytes=-200", size, rangeSatisfiable, 800, 200},
+ {"suffix larger than size clamps", "bytes=-5000", size, rangeSatisfiable, 0, 1000},
+ {"single byte", "bytes=0-0", size, rangeSatisfiable, 0, 1},
+ {"last byte", "bytes=999-999", size, rangeSatisfiable, 999, 1},
+ {"start at eof unsatisfiable", "bytes=1000-1001", size, rangeUnsatisfiable, 0, 0},
+ {"start past eof unsatisfiable", "bytes=2000-", size, rangeUnsatisfiable, 0, 0},
+ {"end before start", "bytes=500-499", size, rangeUnsatisfiable, 0, 0},
+ {"missing unit", "0-100", size, rangeUnsatisfiable, 0, 0},
+ // Multi-range is a valid-but-unsupported form: ignored → full body (200),
+ // not 416. This is the must-fix that stops the non-seekable path from
+ // diverging from the seekable (ServeContent) path on multi-range.
+ {"multi-range ignored", "bytes=0-10,20-30", size, rangeUnsupported, 0, 0},
+ {"empty spec", "bytes=", size, rangeUnsatisfiable, 0, 0},
+ {"no dash", "bytes=100", size, rangeUnsatisfiable, 0, 0},
+ {"suffix zero", "bytes=-0", size, rangeUnsatisfiable, 0, 0},
+ {"negative garbage", "bytes=abc-def", size, rangeUnsatisfiable, 0, 0},
+ // Empty object (size == 0): a WELL-FORMED range has no bytes to satisfy it,
+ // so it is ignored → full (empty) 200, matching stdlib http.ServeContent
+ // rather than diverging with a 416. This covers the maintainer's
+ // zero-length nit. Genuinely malformed / unknown-unit ranges against an
+ // empty object still yield rangeUnsatisfiable (416), also matching stdlib.
+ {"suffix on empty object", "bytes=-100", 0, rangeUnsupported, 0, 0},
+ {"start range on empty object", "bytes=0-", 0, rangeUnsupported, 0, 0},
+ {"mid range on empty object", "bytes=5-10", 0, rangeUnsupported, 0, 0},
+ {"closed range on empty object", "bytes=0-99", 0, rangeUnsupported, 0, 0},
+ // stdlib checks start-vs-size before validating the end, so on an empty
+ // object it ignores (200) even a range with a bad end or reversed bounds;
+ // mirror that. The paired non-empty rows below lock the other half of the
+ // contract: once the start is IN range, the end IS validated → 416.
+ {"bad end on empty object", "bytes=0-abc", 0, rangeUnsupported, 0, 0},
+ {"reversed on empty object", "bytes=10-5", 0, rangeUnsupported, 0, 0},
+ {"bad end on non-empty", "bytes=0-abc", size, rangeUnsatisfiable, 0, 0},
+ {"reversed on non-empty", "bytes=10-5", size, rangeUnsatisfiable, 0, 0},
+ {"unknown unit on empty object", "items=0-10", 0, rangeUnsatisfiable, 0, 0},
+ {"malformed start on empty object", "bytes=abc-def", 0, rangeUnsatisfiable, 0, 0},
+ {"no dash on empty object", "bytes=100", 0, rangeUnsatisfiable, 0, 0},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ start, length, outcome := parseSingleByteRange(tc.header, tc.size)
+ if outcome != tc.wantOutcome {
+ t.Fatalf("outcome = %v, want %v (start=%d length=%d)", outcome, tc.wantOutcome, start, length)
+ }
+ if outcome != rangeSatisfiable {
+ return
+ }
+ if start != tc.wantStart || length != tc.wantLength {
+ t.Fatalf("got (start=%d, length=%d), want (start=%d, length=%d)", start, length, tc.wantStart, tc.wantLength)
+ }
+ })
+ }
+}
+
func TestShouldProxyAttachmentURL(t *testing.T) {
cases := []struct {
raw string