carlos / platform Public

media: download refuses truncation, changed ETags and quoted payloads

Task 2 fix round 1 (Astra P1 x3, Fable).

- Payload refusals log one fixed reason; Payload.Validate names fields,
  never values, so a URL planted in Preset or an output name never
  reaches a log (console's dispatch log still reads well).
- 200 needs Content-Length or chunked framing and answers the first GET
  only; 206 answers a resume only, from the bytes written to the
  object's last byte, Content-Length equal to the range, a "*" total
  only after a known one; a body is whole only at a known size.
- The source must carry one strong, signed If-Match, and every 200/206
  must carry that ETag before a byte is written.
- A 60 s per-read idle timeout resumes within the 20-resume budget.
- Test S3 checks signed header values and gains framing, ETag, range
  and stall knobs; contentRange and unparsable URL tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 796ff7df73b304001d213dc1b0bcba61a22eba75 parent ced7696
8 files changed, +758 −137
  • cmd/carlos-media/main.go +3 −3
  • docs/superpowers/notes/media-conversion-copy-deck.md +2 −1
  • internal/media/payload.go +9 −6
  • internal/media/payload_test.go +41 −0
  • internal/mediahandler/download.go +141 −26
  • internal/mediahandler/download_test.go +414 −53
  • internal/mediahandler/handler.go +13 −4
  • internal/mediahandler/s3test_test.go +135 −44
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go
index 6312f10ea..02ab89035 100644
--- a/cmd/carlos-media/main.go
+++ b/cmd/carlos-media/main.go
@@ -78,9 +78,9 @@ func deadlineCommand(rest []string) int {
// codecCommand is the codec container's entry. It takes no argument
// (the gate compares the command whole), reads the payload and removes
-// it from the environment, so no child the handler starts inherits the
-// transfers, and answers mediahandler.Run's exit. Log lines go to stderr,
-// the task's log.
+// it from the environment, so the job is not inherited by the children
+// the handler starts, and answers mediahandler.Run's exit. Log lines go
+// to stderr, the task's log.
//
// SIGTERM keeps its default action for now: the process dies and writes
// no result, which is what ECS stopping the task asks for. Plan 3 Task 6
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index c79bc9bfb..4c5e54588 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -533,13 +533,14 @@ prints nothing.
| Key | Text |
|---|---|
| `engine.usage` | `usage: carlos-media <deadline\|codec\|selftest\|drill\|version>` (pending Luna pass; plan 3 Task 1) |
-| `engine.codec.payload_refused` | `codec: payload refused: %s` (pending Luna pass; plan 3 Task 2). `%s` is one of `engine.codec.payload.*` or the payload's own shape check (`internal/media` `Payload.Validate`), never a value from the payload |
+| `engine.codec.payload_refused` | `codec: payload refused: %s` (pending Luna pass; plan 3 Task 2). `%s` is one of `engine.codec.payload.*`, never a value from the payload |
| `engine.codec.payload.none` | `no payload` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.payload.too_long` | `payload is over the override limit` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.payload.undecodable` | `payload does not decode as a payload` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.payload.trailing` | `payload has data after the object` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.payload.no_cap` | `payload has no source byte cap` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.payload.no_expiry` | `payload has no grant expiry` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.shape` | `payload does not have the payload's shape` (pending Luna pass; plan 3 Task 2 fix 1). Any refusal by `Payload.Validate`, whose own reason is not logged |
| `engine.codec.scratch` | `codec: scratch directory unusable: %s` (pending Luna pass; plan 3 Task 2). `%s` is the system's error for a path under the scratch directory |
| `engine.codec.grant_expired` | `codec: the grant has expired; no result is written` (pending Luna pass; plan 3 Task 2) |
| `engine.codec.failed` | `codec: failed: %s` (pending Luna pass; plan 3 Task 2). `%s` is the job error code |
diff --git a/internal/media/payload.go b/internal/media/payload.go
index b37eaa0f6..e97124aef 100644
--- a/internal/media/payload.go
+++ b/internal/media/payload.go
@@ -121,17 +121,20 @@ type Payload struct {
// Validate checks the payload's shape: the version, a 32-hex execution, a
// known preset, the three outputs named OutputNames(preset) in order, a
-// GET source and PUT outputs and result.
+// GET source and PUT outputs and result. Its errors never quote a value
+// from the payload (a field could hold a presigned URL, and the codec
+// logs the reason): they name the field, and at most a position or a
+// constant.
func (p Payload) Validate() error {
if p.V != PayloadVersion {
- return fmt.Errorf("payload version %d, want %d", p.V, PayloadVersion)
+ return fmt.Errorf("payload version is not %d", PayloadVersion)
}
if !isExecution(p.Execution) {
return errors.New("payload execution is not 32 hex characters")
}
names := OutputNames(p.Preset)
if names == nil {
- return fmt.Errorf("payload preset %q is unknown", p.Preset)
+ return errors.New("payload preset is unknown")
}
t := p.Transfers
if t.Source.Method != "GET" || t.Source.URL == "" {
@@ -141,14 +144,14 @@ func (p Payload) Validate() error {
return errors.New("payload has no output prefix")
}
if len(t.Outputs) != len(names) {
- return fmt.Errorf("payload has %d outputs, want %d", len(t.Outputs), len(names))
+ return fmt.Errorf("payload does not have %d outputs", len(names))
}
for i, o := range t.Outputs {
if o.Name != names[i] {
- return fmt.Errorf("payload output %d is %q, want %q", i, o.Name, names[i])
+ return fmt.Errorf("payload output %d is not named %s", i, names[i])
}
if o.Method != "PUT" || o.URL != "" {
- return fmt.Errorf("payload output %s is not a PUT under the prefix", o.Name)
+ return fmt.Errorf("payload output %s is not a PUT under the prefix", names[i])
}
}
if t.Result.Method != "PUT" || t.Result.URL == "" {
diff --git a/internal/media/payload_test.go b/internal/media/payload_test.go
index 04d2d70a4..5f14e9093 100644
--- a/internal/media/payload_test.go
+++ b/internal/media/payload_test.go
@@ -227,6 +227,47 @@ func TestPayloadValidate(t *testing.T) {
}
}
+// TestPayloadValidateQuotesNoValue: Validate's reasons name fields, never
+// their values. The codec logs the reason, and a field could hold a
+// presigned URL (plan 3 Task 2 review).
+func TestPayloadValidateQuotesNoValue(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ g := mediatest.NewFakeGrants(func() time.Time { return now })
+ x := "0123456789abcdef0123456789abcdef"
+ tr, exp, err := g.Grant(context.Background(), grantFor("b", "k.mov", "e", x))
+ if err != nil {
+ t.Fatal(err)
+ }
+ good := media.Payload{V: 1, Execution: x, Preset: media.PresetVideo720p, Expiry: exp.Unix(), Transfers: tr}
+ secret := media.Transfers{Shared: tr.Shared}.URL(tr.Source) // a whole presigned URL
+ for name, mutate := range map[string]func(p *media.Payload){
+ "version": func(p *media.Payload) { p.V = 7349 },
+ "execution": func(p *media.Payload) { p.Execution = secret },
+ "preset": func(p *media.Payload) { p.Preset = secret },
+ "output name": func(p *media.Payload) { p.Transfers.Outputs[0].Name = secret },
+ "output count": func(p *media.Payload) {
+ p.Transfers.Outputs = append(p.Transfers.Outputs, media.Transfer{Name: secret})
+ },
+ "output method": func(p *media.Payload) { p.Transfers.Outputs[1].Method = secret },
+ "output url": func(p *media.Payload) { p.Transfers.Outputs[1].URL = secret },
+ "source method": func(p *media.Payload) { p.Transfers.Source.Method = secret },
+ "result method": func(p *media.Payload) { p.Transfers.Result.Method = secret },
+ } {
+ p := good
+ p.Transfers.Outputs = append([]media.Transfer(nil), good.Transfers.Outputs...)
+ mutate(&p)
+ err := p.Validate()
+ if err == nil {
+ t.Fatalf("%s: accepted", name)
+ }
+ for _, bit := range []string{secret, "X-Amz", "s3.test", "7349", "4 outputs"} {
+ if strings.Contains(err.Error(), bit) {
+ t.Errorf("%s: %q quotes %q", name, err, bit)
+ }
+ }
+ }
+}
+
// TestWorstCasePayloadFits: the longest admitted key, a multipart ETag, a
// 1,400-character token and 64-hex signatures, inside the RunTask override
// structure plan 3 builds, fit MaxOverrideBytes (spec §5.5).
diff --git a/internal/mediahandler/download.go b/internal/mediahandler/download.go
index 39c764b93..b65aed84a 100644
--- a/internal/mediahandler/download.go
+++ b/internal/mediahandler/download.go
@@ -6,6 +6,7 @@ import (
"io"
"net"
"net/http"
+ "net/url"
"os"
"strconv"
"strings"
@@ -79,25 +80,58 @@ func waitCtx(ctx context.Context, d time.Duration) error {
}
}
+// idleTimeout is how long a body may send nothing before the attempt is
+// treated as a broken connection and resumed (within maxResumes).
+const idleTimeout = 60 * time.Second
+
+// idleTimer is the part of *time.Timer the idle check uses.
+type idleTimer interface {
+ Reset(time.Duration) bool
+ Stop() bool
+}
+
+// newIdleTimer is a stopped timer that runs f when it fires.
+func newIdleTimer(d time.Duration, f func()) idleTimer {
+ t := time.AfterFunc(d, f)
+ t.Stop()
+ return t
+}
+
// download streams the source to dst (which must not exist) with the
// source transfer: its signed headers exactly, plus Accept-Encoding:
// identity, and on a resume Range: bytes=<written>-. Rules:
//
+// - the source transfer must carry one strong If-Match, named in its
+// X-Amz-SignedHeaders, else engine_failed before any request;
// - before every attempt, now at or after the expiry is errGrantExpired;
// no transfer begins after the grant (spec §5.4);
-// - 200 with a Content-Length over the cap is source_too_large before
-// any byte is read; every byte is counted as it streams, and one past
-// the cap is source_too_large;
+// - every 200 or 206 must carry the If-Match ETag (else source_changed,
+// or unreadable when it has none) before a byte is written;
+// - 200 answers the first GET only, with a Content-Length (over the cap
+// is source_too_large before any byte is read) or chunked; a body
+// delimited by the connection's close is unreadable;
+// - 206 answers a resume only; its Content-Range must start at the bytes
+// written and end at the object's last byte, its total must be the
+// total seen before (a "*" total needs one seen before), and its
+// Content-Length must be the range's length; else unreadable;
+// - every byte is counted as it streams, and one past the cap is
+// source_too_large;
+// - a body ending cleanly is the whole download only when a total is
+// known and every byte of it has been written; else unreadable;
// - 404 source_not_found, 412 source_changed; 403 at or after the
// expiry errGrantExpired, before it source_unreadable; 500, 502, 503
// and 504 are retried as a broken connection; any other status is
// source_unreadable;
-// - a broken connection or body resumes after resumeDelay, under the
-// same If-Match; a resume must answer 206 from the byte asked for,
-// else unreadable; past maxResumes resumes, unreadable.
+// - a broken connection or body, or idleTimeout with no body bytes,
+// resumes after resumeDelay under the same If-Match; past maxResumes
+// resumes, unreadable.
//
// On any failure dst is removed. ctx's error is returned as it is.
func download(ctx context.Context, cfg Config, p media.Payload, dst string) (err error) {
+ ifMatch, ok := signedIfMatch(p.Transfers.Source)
+ if !ok {
+ return jobError{media.CodeEngineFailed}
+ }
f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return jobError{media.CodeEngineFailed}
@@ -111,7 +145,7 @@ func download(ctx context.Context, cfg Config, p media.Payload, dst string) (err
os.Remove(dst)
}
}()
- d := &fetch{cfg: cfg, p: p, f: f, expiry: time.Unix(p.Expiry, 0), total: -1}
+ d := &fetch{cfg: cfg, p: p, f: f, ifMatch: ifMatch, expiry: time.Unix(p.Expiry, 0), total: -1}
for resumes := 0; ; resumes++ {
if !cfg.Now().Before(d.expiry) {
return errGrantExpired
@@ -133,11 +167,37 @@ func download(ctx context.Context, cfg Config, p media.Payload, dst string) (err
}
}
+// signedIfMatch is the source transfer's If-Match: exactly one header of
+// that name (in any case), a strong ETag ("…", not W/"…"), and if-match
+// among the query's X-Amz-SignedHeaders, so the store checks it.
+func signedIfMatch(src media.Transfer) (string, bool) {
+ value, n := "", 0
+ for k, v := range src.Header {
+ if http.CanonicalHeaderKey(k) == "If-Match" {
+ value, n = v, n+1
+ }
+ }
+ if n != 1 || len(value) < 3 || value[0] != '"' || value[len(value)-1] != '"' || strings.Contains(value[1:len(value)-1], `"`) {
+ return "", false
+ }
+ q, err := url.ParseQuery(src.Query)
+ if err != nil {
+ return "", false
+ }
+ for _, h := range strings.Split(q.Get("X-Amz-SignedHeaders"), ";") {
+ if h == "if-match" {
+ return value, true
+ }
+ }
+ return "", false
+}
+
// fetch is one download's state across its attempts.
type fetch struct {
cfg Config
p media.Payload
f *os.File
+ ifMatch string
expiry time.Time
written int64
total int64 // the object's size once a response has said it; -1 before
@@ -148,7 +208,9 @@ type fetch struct {
// Neither ever carries the request's URL.
func (d *fetch) attempt(ctx context.Context) (broken bool, err error) {
src := d.p.Transfers.Source
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.p.Transfers.URL(src), nil)
+ actx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ req, err := http.NewRequestWithContext(actx, http.MethodGet, d.p.Transfers.URL(src), nil)
if err != nil {
// url.Parse's error quotes the URL: drop it.
return false, jobError{media.CodeEngineFailed}
@@ -177,10 +239,11 @@ func (d *fetch) attempt(ctx context.Context) (broken bool, err error) {
}
return false, err
}
- return d.stream(ctx, resp.Body)
+ return d.stream(ctx, resp.Body, cancel)
}
-// check decides what a response's status and size headers allow.
+// check decides what a response's status and headers allow, before any
+// byte of its body is read.
func (d *fetch) check(resp *http.Response) error {
limit := d.p.Limits.SourceBytes
switch resp.StatusCode {
@@ -192,21 +255,46 @@ func (d *fetch) check(resp *http.Response) error {
if resp.ContentLength > limit {
return jobError{media.CodeSourceTooLarge}
}
+ if resp.ContentLength < 0 && !chunked(resp) {
+ // Delimited by the connection's close, a cut body would
+ // look whole.
+ return jobError{media.CodeUnreadable}
+ }
+ if err := d.sameObject(resp); err != nil {
+ return err
+ }
d.total = resp.ContentLength
return nil
case http.StatusPartialContent:
- // Content-Range must continue from the bytes written, at the size
- // the store gave before; a 206 to the first GET must start at 0.
- start, total, ok := contentRange(resp.Header.Get("Content-Range"))
- if !ok || start != d.written || (d.total >= 0 && total >= 0 && total != d.total) {
+ if d.written == 0 {
+ // No Range was sent.
+ return jobError{media.CodeUnreadable}
+ }
+ start, end, total, ok := contentRange(resp.Header.Get("Content-Range"))
+ if !ok || start != d.written {
+ return jobError{media.CodeUnreadable}
+ }
+ if total < 0 {
+ // "*" stands only for the total an earlier answer gave. With
+ // none, total stays -1 and the end check below refuses it:
+ // the object's size is unknown.
+ total = d.total
+ }
+ if d.total >= 0 && total != d.total {
return jobError{media.CodeUnreadable}
}
if total > limit {
return jobError{media.CodeSourceTooLarge}
}
- if total >= 0 {
- d.total = total
+ // The resume asked for the rest of the object, and the body
+ // must be exactly that range.
+ if end != total-1 || (resp.ContentLength >= 0 && resp.ContentLength != end-start+1) {
+ return jobError{media.CodeUnreadable}
}
+ if err := d.sameObject(resp); err != nil {
+ return err
+ }
+ d.total = total
return nil
case http.StatusNotFound:
return jobError{media.CodeSourceNotFound}
@@ -223,16 +311,41 @@ func (d *fetch) check(resp *http.Response) error {
return jobError{media.CodeSourceUnreadable}
}
+// sameObject requires the response to be of the object If-Match names: a
+// store that ignored the condition would answer another object's ETag.
+// Every response is held to the signed value, so every response of one
+// download carries the same ETag.
+func (d *fetch) sameObject(resp *http.Response) error {
+ switch resp.Header.Get("ETag") {
+ case d.ifMatch:
+ return nil
+ case "":
+ return jobError{media.CodeUnreadable}
+ }
+ return jobError{media.CodeSourceChanged}
+}
+
+// chunked reports whether the body is framed by chunked encoding.
+func chunked(resp *http.Response) bool {
+ return len(resp.TransferEncoding) > 0 && resp.TransferEncoding[0] == "chunked"
+}
+
// errRetry is a status the store answers when it may do better on a
// retry; attempt turns it into a broken connection.
var errRetry = errors.New("retry")
// stream copies body to the file, counting every byte against the cap.
-func (d *fetch) stream(ctx context.Context, body io.Reader) (broken bool, err error) {
+// Each read must bring bytes within idleTimeout, or cancel ends the
+// attempt as a broken connection.
+func (d *fetch) stream(ctx context.Context, body io.Reader, cancel func()) (broken bool, err error) {
limit := d.p.Limits.SourceBytes
+ idle := d.cfg.idle(idleTimeout, cancel)
+ defer idle.Stop()
buf := make([]byte, readChunk)
for {
+ idle.Reset(idleTimeout)
n, rerr := body.Read(buf)
+ idle.Stop()
if n > 0 {
if d.written+int64(n) > limit {
return false, jobError{media.CodeSourceTooLarge}
@@ -246,7 +359,9 @@ func (d *fetch) stream(ctx context.Context, body io.Reader) (broken bool, err er
case rerr == nil:
continue
case rerr == io.EOF:
- if d.total >= 0 && d.written != d.total {
+ // Whole only when the object's size is known and every
+ // byte of it is here.
+ if d.total < 0 || d.written != d.total {
return false, jobError{media.CodeUnreadable}
}
return false, nil
@@ -258,30 +373,30 @@ func (d *fetch) stream(ctx context.Context, body io.Reader) (broken bool, err er
}
// contentRange reads "bytes <start>-<end>/<total>" (total "*" is -1).
-func contentRange(h string) (start, total int64, ok bool) {
+func contentRange(h string) (start, end, total int64, ok bool) {
rest, found := strings.CutPrefix(h, "bytes ")
if !found {
- return 0, 0, false
+ return 0, 0, 0, false
}
span, size, found := strings.Cut(rest, "/")
if !found {
- return 0, 0, false
+ return 0, 0, 0, false
}
first, last, found := strings.Cut(span, "-")
if !found {
- return 0, 0, false
+ return 0, 0, 0, false
}
start, err1 := strconv.ParseInt(first, 10, 64)
end, err2 := strconv.ParseInt(last, 10, 64)
if err1 != nil || err2 != nil || start < 0 || end < start {
- return 0, 0, false
+ return 0, 0, 0, false
}
if size == "*" {
- return start, -1, true
+ return start, end, -1, true
}
total, err := strconv.ParseInt(size, 10, 64)
if err != nil || total <= end {
- return 0, 0, false
+ return 0, 0, 0, false
}
- return start, total, true
+ return start, end, total, true
}
diff --git a/internal/mediahandler/download_test.go b/internal/mediahandler/download_test.go
index d266719dc..30f03389b 100644
--- a/internal/mediahandler/download_test.go
+++ b/internal/mediahandler/download_test.go
@@ -79,7 +79,9 @@ func (h *harness) Delays() []time.Duration {
// download runs download into <scratch>/in/source with a 20 s limit.
func (h *harness) download(t *testing.T, p media.Payload) error {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ // 5 s: a handler that read a held body would wait this long and
+ // answer the context's error.
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return download(ctx, h.cfg.withDefaults(), p, sourcePath(h.cfg))
}
@@ -285,18 +287,29 @@ func TestDownloadSourceChanged(t *testing.T) {
}
// TestDownloadCapWhileStreaming: with no Content-Length, a body one byte
-// past the cap is source_too_large and the scratch file is removed; a
-// body exactly at the cap downloads.
+// past the cap is source_too_large and the scratch file is removed. A
+// chunked body at the cap whose size no answer gave is unreadable (a
+// download is whole only at a known size); a resume's Content-Range can
+// give it. With a Content-Length, exactly the cap downloads.
func TestDownloadCapWhileStreaming(t *testing.T) {
for _, c := range []struct {
- size int
- want string
- }{{mib + 1, media.CodeSourceTooLarge}, {mib, "nil"}} {
- t.Run(fmt.Sprint(c.size), func(t *testing.T) {
+ name string
+ size int
+ chunked bool
+ cuts []int64
+ want string
+ }{
+ {"one past the cap", mib + 1, true, nil, media.CodeSourceTooLarge},
+ {"at the cap, no size", mib, true, nil, media.CodeUnreadable},
+ {"at the cap, size from the resume", mib, true, []int64{mib / 2}, "nil"},
+ {"at the cap, Content-Length", mib, false, nil, "nil"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
h := newHarness(t)
data := randomBytes(t, c.size)
p := h.s.payload(t, media.PresetVideo720p, data, mib)
- h.s.Chunked = true
+ h.s.Chunked = c.chunked
+ h.s.Cuts = c.cuts
if err := h.download(t, p); codeOf(err) != c.want {
t.Fatalf("download of %d bytes under a %d cap = %s, want %s", c.size, mib, codeOf(err), c.want)
}
@@ -316,7 +329,7 @@ func TestDownloadCapWhileStreaming(t *testing.T) {
func TestDownloadContentLengthOverCap(t *testing.T) {
h := newHarness(t)
p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, mib+1), mib)
- h.s.HoldBody = true
+ h.s.HoldGet = 1
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := download(ctx, h.cfg.withDefaults(), p, sourcePath(h.cfg)); codeOf(err) != media.CodeSourceTooLarge {
@@ -478,18 +491,27 @@ func TestDownloadStatuses(t *testing.T) {
})
}
-// TestDownloadResumeMustContinue: a resume answered with a 200 (the
-// Range ignored) or a 206 from another offset is unreadable.
+// TestDownloadResumeMustContinue: each wrong answer to a resume is
+// refused. Where the fault is in the headers, the server then holds the
+// body, so a handler that read it would hang to its context instead: the
+// refusal comes before a byte is written.
func TestDownloadResumeMustContinue(t *testing.T) {
for _, c := range []struct {
- name string
- fault func(*s3Server)
+ name string
+ firstChunked bool
+ fault func(*s3Server)
+ want string
}{
- {"range ignored", func(s *s3Server) { s.IgnoreRange = true }},
- {"another offset", func(s *s3Server) { s.SkewRange = 1 }},
- // With no size known (a chunked first answer, a "*" total) only
- // the offset check can see the gap.
- {"another offset, no size", func(s *s3Server) { s.SkewRange, s.NoTotal = 1, true }},
+ {"range ignored (200)", true, func(s *s3Server) { s.IgnoreRange, s.HoldGet = true, 2 }, media.CodeUnreadable},
+ {"another offset", false, func(s *s3Server) { s.SkewRange, s.HoldGet = 1, 2 }, media.CodeUnreadable},
+ {"total grew", false, func(s *s3Server) { s.TotalLie, s.HoldGet = 1, 2 }, media.CodeUnreadable},
+ {"total shrank", false, func(s *s3Server) { s.TotalLie, s.HoldGet = -1000, 2 }, media.CodeUnreadable},
+ {"range ends before the object", false, func(s *s3Server) { s.ShortRange, s.HoldGet = 2, 2 }, media.CodeUnreadable},
+ {"Content-Length is not the range's", false, func(s *s3Server) { s.LengthLie, s.HoldGet = 1, 2 }, media.CodeUnreadable},
+ {"total over the cap", true, func(s *s3Server) { s.TotalLie, s.HoldGet = 8*mib, 2 }, media.CodeSourceTooLarge},
+ {"no ETag", false, func(s *s3Server) { s.NoETag, s.HoldGet = true, 2 }, media.CodeUnreadable},
+ // A chunked body that ends cleanly short of its Content-Range.
+ {"body short of its range", false, func(s *s3Server) { s.Chunked, s.TrimBody = true, 1 }, media.CodeUnreadable},
} {
t.Run(c.name, func(t *testing.T) {
h := newHarness(t)
@@ -497,7 +519,7 @@ func TestDownloadResumeMustContinue(t *testing.T) {
// body again would also pass it.
p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 2*mib)
h.s.Cuts = []int64{mib}
- h.s.Chunked = true
+ h.s.Chunked = c.firstChunked
h.s.OnGet = func(n int) int {
if n == 2 {
h.s.mu.Lock()
@@ -506,8 +528,8 @@ func TestDownloadResumeMustContinue(t *testing.T) {
}
return 0
}
- if err := h.download(t, p); codeOf(err) != media.CodeUnreadable {
- t.Fatalf("download = %s, want unreadable", codeOf(err))
+ if err := h.download(t, p); codeOf(err) != c.want {
+ t.Fatalf("download = %s, want %s", codeOf(err), c.want)
}
if rs := h.s.Requests(); len(rs) != 2 {
t.Fatalf("%d requests, want 2", len(rs))
@@ -517,6 +539,338 @@ func TestDownloadResumeMustContinue(t *testing.T) {
}
}
+// TestDownloadUnknownSizeIsNeverWhole is Astra's case: a chunked first
+// answer breaks after 4 bytes, and the resume answers "bytes 4-5/*" with
+// 2 bytes and a clean end. Nothing ever gave the object's size, so the
+// download fails rather than keep 6 bytes of a 10-byte object.
+//
+// The held variant answers "bytes 4-9/*" (the whole rest) and then sends
+// nothing: the "*" is refused from the headers, before a byte is read.
+func TestDownloadUnknownSizeIsNeverWhole(t *testing.T) {
+ for _, held := range []bool{false, true} {
+ t.Run(fmt.Sprint("held ", held), func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, []byte("0123456789"), mib)
+ h.s.Chunked = true
+ h.s.Cuts = []int64{4}
+ h.s.NoTotal = true
+ if held {
+ h.s.HoldGet = 2
+ } else {
+ h.s.ShortRange = 2
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeUnreadable {
+ t.Fatalf("download = %s, want unreadable", codeOf(err))
+ }
+ rs := h.s.Requests()
+ if len(rs) != 2 || rs[1].Header.Get("Range") != "bytes=4-" {
+ t.Fatalf("requests %+v, want a cut GET then a resume from 4", rs)
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// TestDownloadFirstAnswerMustBeFramed: a 200 delimited only by the
+// connection's close, and a 206 to a GET that sent no Range, are
+// unreadable before any byte is read (the server then sends nothing).
+func TestDownloadFirstAnswerMustBeFramed(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ fault func(*s3Server)
+ }{
+ {"close-delimited 200", func(s *s3Server) { s.CloseDelimited = true }},
+ {"206 with no Range", func(s *s3Server) { s.PartialFirst, s.HoldGet = true, 1 }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 4096), mib)
+ c.fault(h.s)
+ if err := h.download(t, p); codeOf(err) != media.CodeUnreadable {
+ t.Fatalf("download = %s, want unreadable", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != 1 {
+ t.Fatalf("%d requests, want 1", len(rs))
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// TestDownloadRefusesAChangedETag: a store that ignores If-Match and
+// answers another object's ETag is source_changed before a byte of it is
+// written, on the first GET or on a resume (which here also brings
+// different bytes). The server holds the body after the headers.
+func TestDownloadRefusesAChangedETag(t *testing.T) {
+ for _, at := range []int{1, 2} {
+ t.Run(fmt.Sprint("GET ", at), func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.IgnoreIfMatch = true
+ h.s.OnGet = func(n int) int {
+ if n == at {
+ h.s.SetSource(randomBytes(t, 2*mib), "another-etag", "")
+ h.s.mu.Lock()
+ h.s.HoldGet = at
+ h.s.mu.Unlock()
+ }
+ return 0
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeSourceChanged {
+ t.Fatalf("download = %s, want source_changed", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != at {
+ t.Fatalf("%d requests, want %d", len(rs), at)
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// fakeIdle stands in for the idle timer: the test fires it by hand when
+// the server has stalled (stall), and a timer armed after that fires at
+// once.
+type fakeIdle struct {
+ mu sync.Mutex
+ armed bool
+ fire func()
+ stalled bool
+ durations []time.Duration
+}
+
+type fakeIdleTimer struct {
+ fi *fakeIdle
+ f func()
+}
+
+func (fi *fakeIdle) new(d time.Duration, f func()) idleTimer {
+ fi.mu.Lock()
+ defer fi.mu.Unlock()
+ fi.durations = append(fi.durations, d)
+ return &fakeIdleTimer{fi: fi, f: f}
+}
+
+func (t *fakeIdleTimer) Reset(time.Duration) bool {
+ t.fi.mu.Lock()
+ defer t.fi.mu.Unlock()
+ t.fi.armed, t.fi.fire = true, t.f
+ if t.fi.stalled {
+ t.fi.stalled = false
+ t.f()
+ }
+ return false
+}
+
+func (t *fakeIdleTimer) Stop() bool {
+ t.fi.mu.Lock()
+ defer t.fi.mu.Unlock()
+ t.fi.armed = false
+ return false
+}
+
+// stall fires the armed timer, or the next one armed.
+func (fi *fakeIdle) stall() {
+ fi.mu.Lock()
+ defer fi.mu.Unlock()
+ if fi.armed {
+ fi.fire()
+ return
+ }
+ fi.stalled = true
+}
+
+// TestDownloadIdleTimeoutResumes: a body that stops sending is, once the
+// idle timer (60 s) fires, a broken connection: the download resumes
+// from the bytes written and completes.
+func TestDownloadIdleTimeoutResumes(t *testing.T) {
+ h := newHarness(t)
+ fi := &fakeIdle{}
+ h.cfg.idle = fi.new
+ data := randomBytes(t, 2*mib)
+ p := h.s.payload(t, media.PresetVideo720p, data, 8*mib)
+ h.s.StallAt = mib
+ go func() {
+ <-h.s.Stalled
+ fi.stall()
+ }()
+ if err := h.download(t, p); err != nil {
+ t.Fatalf("download: %s", codeOf(err))
+ }
+ h.wantSource(t, data)
+ rs := h.s.Requests()
+ if len(rs) != 2 {
+ t.Fatalf("%d requests, want 2 (a stalled GET and a resume)", len(rs))
+ }
+ var from int64
+ if _, err := fmt.Sscanf(rs[1].Header.Get("Range"), "bytes=%d-", &from); err != nil || from < 1 || from > mib {
+ t.Fatalf("resume Range %q, want bytes=N- with 0 < N <= %d", rs[1].Header.Get("Range"), mib)
+ }
+ if d := h.Delays(); len(d) != 1 || d[0] != time.Second {
+ t.Errorf("delays %v, want [1s]", d)
+ }
+ fi.mu.Lock()
+ defer fi.mu.Unlock()
+ for _, d := range fi.durations {
+ if d != 60*time.Second {
+ t.Errorf("idle timer of %v, want 60s", d)
+ }
+ }
+}
+
+// TestDownloadRefusesAnUnsignedSource: the source transfer must carry
+// exactly one strong If-Match that its query signs; anything else is
+// engine_failed before any request. A lower-case header name is fine.
+func TestDownloadRefusesAnUnsignedSource(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ fault func(*media.Transfer)
+ want string
+ }{
+ {"no If-Match", func(s *media.Transfer) { delete(s.Header, "If-Match") }, media.CodeEngineFailed},
+ {"two If-Match", func(s *media.Transfer) { s.Header["if-match"] = s.Header["If-Match"] }, media.CodeEngineFailed},
+ {"weak", func(s *media.Transfer) { s.Header["If-Match"] = `W/"` + testETag + `"` }, media.CodeEngineFailed},
+ {"unquoted", func(s *media.Transfer) { s.Header["If-Match"] = testETag }, media.CodeEngineFailed},
+ {"empty", func(s *media.Transfer) { s.Header["If-Match"] = `""` }, media.CodeEngineFailed},
+ {"not signed", func(s *media.Transfer) {
+ s.Query = strings.Replace(s.Query, "X-Amz-SignedHeaders=host%3Bif-match", "X-Amz-SignedHeaders=host", 1)
+ }, media.CodeEngineFailed},
+ {"lower-case name", func(s *media.Transfer) {
+ s.Header["if-match"] = s.Header["If-Match"]
+ delete(s.Header, "If-Match")
+ }, "nil"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 4096)
+ p := h.s.payload(t, media.PresetVideo720p, data, mib)
+ src := p.Transfers.Source
+ src.Header = map[string]string{}
+ for k, v := range p.Transfers.Source.Header {
+ src.Header[k] = v
+ }
+ if !strings.Contains(src.Query, "X-Amz-SignedHeaders=host%3Bif-match") {
+ t.Fatal("the test payload's source query changed shape")
+ }
+ c.fault(&src)
+ p.Transfers.Source = src
+ if err := h.download(t, p); codeOf(err) != c.want {
+ t.Fatalf("download = %s, want %s", codeOf(err), c.want)
+ }
+ if c.want == "nil" {
+ h.wantSource(t, data)
+ return
+ }
+ if n := len(h.s.Requests()); n != 0 {
+ t.Fatalf("%d requests, want none", n)
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// TestDownloadUnparsableURL: a source URL Go cannot parse is
+// engine_failed with no request, and the error does not quote it.
+func TestDownloadUnparsableURL(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), mib)
+ p.Transfers.Source.URL = h.s.srv.URL + "/src/%zz"
+ err := h.download(t, p)
+ if codeOf(err) != media.CodeEngineFailed {
+ t.Fatalf("download = %s, want engine_failed", codeOf(err))
+ }
+ if strings.Contains(err.Error(), "%zz") || strings.Contains(err.Error(), h.s.srv.URL) {
+ t.Fatalf("error %q quotes the URL", err)
+ }
+ if n := len(h.s.Requests()); n != 0 {
+ t.Fatalf("%d requests, want none", n)
+ }
+ h.wantNoSource(t)
+}
+
+func TestContentRange(t *testing.T) {
+ for h, want := range map[string]struct {
+ start, end, total int64
+ ok bool
+ }{
+ "bytes 0-9/10": {0, 9, 10, true},
+ "bytes 4-9/10": {4, 9, 10, true},
+ "bytes 4-5/*": {4, 5, -1, true},
+ "bytes 5-4/10": {ok: false}, // end < start
+ "bytes 0-9/9": {ok: false}, // total <= end
+ "bytes 0-9/0": {ok: false},
+ "bytes -1-9/10": {ok: false},
+ "bytes 0-9": {ok: false},
+ "bytes */10": {ok: false},
+ "items 0-9/10": {ok: false},
+ "bytes 0-x/10": {ok: false},
+ "bytes 0-9/ten": {ok: false},
+ "": {ok: false},
+ "bytes 0-9/10 ": {ok: false},
+ "bytes 00-9/10": {0, 9, 10, true},
+ "bytes 0-9/10/11": {ok: false},
+ } {
+ s, e, tot, ok := contentRange(h)
+ if ok != want.ok || ok && (s != want.start || e != want.end || tot != want.total) {
+ t.Errorf("contentRange(%q) = %d %d %d %v, want %+v", h, s, e, tot, ok, want)
+ }
+ }
+}
+
+// TestS3ServerChecksSignedHeaderValues: the test store refuses (403) and
+// records a request whose signed header is missing, repeated or has
+// another value, for a GET and for a PUT, and honours If-None-Match.
+// Task 6's upload tests rely on it.
+func TestS3ServerChecksSignedHeaderValues(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), mib)
+ tr := p.Transfers
+ send := func(method string, x media.Transfer, header map[string][]string) int {
+ t.Helper()
+ req, err := http.NewRequest(method, tr.URL(x), strings.NewReader("{}"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k, vs := range header {
+ for _, v := range vs {
+ req.Header.Add(k, v)
+ }
+ }
+ resp, err := h.s.srv.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ return resp.StatusCode
+ }
+ good := `"` + testETag + `"`
+ for _, c := range []struct {
+ name string
+ method string
+ x media.Transfer
+ header map[string][]string
+ want int
+ bad bool
+ }{
+ {"GET right", "GET", tr.Source, map[string][]string{"If-Match": {good}}, 200, false},
+ {"GET no If-Match", "GET", tr.Source, nil, 403, true},
+ {"GET other If-Match", "GET", tr.Source, map[string][]string{"If-Match": {`"other"`}}, 403, true},
+ {"GET two If-Match", "GET", tr.Source, map[string][]string{"If-Match": {good, good}}, 403, true},
+ {"PUT other Content-Type", "PUT", tr.Result, map[string][]string{"Content-Type": {"text/plain"}, "If-None-Match": {"*"}}, 403, true},
+ {"PUT no If-None-Match", "PUT", tr.Result, map[string][]string{"Content-Type": {"application/json"}}, 403, true},
+ {"PUT right", "PUT", tr.Result, map[string][]string{"Content-Type": {"application/json"}, "If-None-Match": {"*"}}, 200, false},
+ {"PUT again", "PUT", tr.Result, map[string][]string{"Content-Type": {"application/json"}, "If-None-Match": {"*"}}, 412, false},
+ } {
+ before := len(h.s.Problems())
+ if got := send(c.method, c.x, c.header); got != c.want {
+ t.Errorf("%s: status %d, want %d", c.name, got, c.want)
+ }
+ if recorded := len(h.s.Problems()) > before; recorded != c.bad {
+ t.Errorf("%s: problem recorded %v, want %v", c.name, recorded, c.bad)
+ }
+ }
+}
+
// TestDownloadGivesUpAfter20Resumes: a body that breaks 21 times is
// unreadable after exactly 20 resumes, each from the bytes written, with
// the delays 1, 2, 4, 8 s and then 10 s.
@@ -637,6 +991,15 @@ func TestRunRejectsABadPayload(t *testing.T) {
if n := len(h.s.Requests()); n != 0 {
t.Fatalf("bad payloads made %d requests", n)
}
+ // A payload Validate refuses is logged with one fixed reason,
+ // whatever Validate's own message says.
+ for _, name := range []string{"version 2", "31-hex execution", "unknown preset", "two outputs"} {
+ before := len(h.Logs())
+ Run(context.Background(), cfg, cases[name])
+ if got := h.Logs()[before:]; len(got) != 1 || got[0] != "codec: payload refused: payload does not have the payload's shape" {
+ t.Errorf("%s: logged %q", name, got)
+ }
+ }
if ents, _ := os.ReadDir(scratch); len(ents) != 0 {
t.Fatalf("a bad payload touched the scratch: %v", ents)
}
@@ -752,6 +1115,18 @@ func TestHandlerNeverLogsTransfers(t *testing.T) {
Run(context.Background(), h.cfg, bad[:len(bad)-40])
// json's unknown-field error quotes the field's name.
Run(context.Background(), h.cfg, strings.Replace(bad, `{"v":1,`, `{"v":1,"X-Amz-Signature=`+testToken+`":1,`, 1))
+ // A presigned URL where Validate looks (Fable's cases).
+ signedURL := p.Transfers.URL(p.Transfers.Source)
+ inPreset := h.s.payload(t, media.PresetVideo720p, nil, mib)
+ inPreset.Preset = signedURL
+ Run(context.Background(), h.cfg, marshal(t, inPreset))
+ inName := h.s.payload(t, media.PresetVideo720p, nil, mib)
+ inName.Transfers.Outputs = append([]media.Transfer(nil), inName.Transfers.Outputs...)
+ inName.Transfers.Outputs[0].Name = inName.Transfers.URL(inName.Transfers.Outputs[0])
+ Run(context.Background(), h.cfg, marshal(t, inName))
+ if n := len(h.Logs()); n != 5 {
+ t.Fatalf("%d refusal lines, want 5", n)
+ }
check("bad payload", h, h.Logs())
if len(all) == 0 {
t.Fatal("no log lines were checked")
@@ -763,9 +1138,12 @@ func TestHandlerNeverLogsTransfers(t *testing.T) {
func TestConfigDefaults(t *testing.T) {
t.Setenv(ScratchEnv, "")
c := Config{}.withDefaults()
- if c.FFmpeg != "/usr/bin/ffmpeg" || c.FFprobe != "/usr/bin/ffprobe" || c.Scratch != "/scratch" || c.Now == nil || c.Logf == nil || c.wait == nil || c.HTTP == nil {
+ if c.FFmpeg != "/usr/bin/ffmpeg" || c.FFprobe != "/usr/bin/ffprobe" || c.Scratch != "/scratch" || c.Now == nil || c.Logf == nil || c.wait == nil || c.idle == nil || c.HTTP == nil {
t.Fatalf("defaults %+v", c)
}
+ if idleTimeout != 60*time.Second {
+ t.Fatalf("idleTimeout = %v, want 60s (the controller's ruling)", idleTimeout)
+ }
t.Setenv(ScratchEnv, "/var/media/x1")
if got := (Config{}).withDefaults().Scratch; got != "/var/media/x1" {
t.Fatalf("Scratch = %q, want the environment's", got)
@@ -775,36 +1153,19 @@ func TestConfigDefaults(t *testing.T) {
}
}
-// TestDownloadResumeSizeMustAgree: a resume whose Content-Range total
-// differs from the size the first answer gave is unreadable; with no
-// size before (a chunked first answer), a body that ends short of the
-// total it claimed is unreadable, and a claimed total over the cap is
-// source_too_large.
-func TestDownloadResumeSizeMustAgree(t *testing.T) {
- for _, c := range []struct {
- name string
- chunked bool
- lie int64
- want string
- }{
- {"total grew", false, 1, media.CodeUnreadable},
- {"total shrank", false, -1000, media.CodeUnreadable},
- {"ends short of its total", true, 1, media.CodeUnreadable},
- {"total over the cap", true, 8 * mib, media.CodeSourceTooLarge},
- } {
- t.Run(c.name, func(t *testing.T) {
- h := newHarness(t)
- p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
- h.s.Cuts = []int64{mib}
- h.s.Chunked = c.chunked
- h.s.TotalLie = c.lie
- if err := h.download(t, p); codeOf(err) != c.want {
- t.Fatalf("download = %s, want %s", codeOf(err), c.want)
- }
- if rs := h.s.Requests(); len(rs) != 2 {
- t.Fatalf("%d requests, want 2", len(rs))
- }
- h.wantNoSource(t)
- })
+// TestDownloadStarTotalAfterAKnownSize: once the first answer gave the
+// size, a resume whose Content-Range total is "*" is accepted against it.
+func TestDownloadStarTotalAfterAKnownSize(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 2*mib)
+ p := h.s.payload(t, media.PresetVideo720p, data, 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.NoTotal = true
+ if err := h.download(t, p); err != nil {
+ t.Fatalf("download: %s", codeOf(err))
+ }
+ h.wantSource(t, data)
+ if rs := h.s.Requests(); len(rs) != 2 || rs[1].Status != http.StatusPartialContent {
+ t.Fatalf("requests %+v, want a cut GET then a 206", rs)
}
}
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go
index 54e7dc190..f302d7c16 100644
--- a/internal/mediahandler/handler.go
+++ b/internal/mediahandler/handler.go
@@ -53,6 +53,9 @@ type Config struct {
// wait sleeps before a resume; nil is a timer that honours ctx.
// Tests replace it to record the delays without waiting.
wait func(ctx context.Context, d time.Duration) error
+ // idle makes the per-read idle timer; nil is newIdleTimer. Tests
+ // replace it to fire the timer by hand.
+ idle func(d time.Duration, f func()) idleTimer
}
// withDefaults fills every unset field.
@@ -83,6 +86,9 @@ func (c Config) withDefaults() Config {
if c.wait == nil {
c.wait = waitCtx
}
+ if c.idle == nil {
+ c.idle = newIdleTimer
+ }
return c
}
@@ -110,7 +116,8 @@ func Run(ctx context.Context, cfg Config, payload string) int {
p, err := parsePayload(payload)
if err != nil {
// engine.codec.payload_refused (pending Luna pass). The reason
- // names a field or a shape, never a value from the payload.
+ // is one of parsePayload's fixed strings, never a value from the
+ // payload.
cfg.Logf("codec: payload refused: %v", err)
return media.ExitFailed
}
@@ -155,7 +162,7 @@ func sourcePath(cfg Config) string { return filepath.Join(cfg.Scratch, "in", "so
// parsePayload decodes the payload strictly (no unknown field, nothing
// after the object, at most media.MaxOverrideBytes) and checks it:
// Validate's shape, a positive byte cap and a positive expiry. Its errors
-// never quote the payload.
+// are fixed strings: none quotes the payload.
func parsePayload(s string) (media.Payload, error) {
if s == "" {
return media.Payload{}, errors.New("no payload")
@@ -173,8 +180,10 @@ func parsePayload(s string) (media.Payload, error) {
if _, err := dec.Token(); err != io.EOF {
return media.Payload{}, errors.New("payload has data after the object")
}
- if err := p.Validate(); err != nil {
- return media.Payload{}, err
+ if p.Validate() != nil {
+ // Validate names fields, not values, but the log line stays
+ // fixed whatever it says (plan 3 Task 2 review, P1).
+ return media.Payload{}, errors.New("payload does not have the payload's shape")
}
if p.Limits.SourceBytes <= 0 {
return media.Payload{}, errors.New("payload has no source byte cap")
diff --git a/internal/mediahandler/s3test_test.go b/internal/mediahandler/s3test_test.go
index fa4cfced0..7d3e72b57 100644
--- a/internal/mediahandler/s3test_test.go
+++ b/internal/mediahandler/s3test_test.go
@@ -55,8 +55,9 @@ type s3Object struct {
// s3Transfer is what the server presigned on one path.
type s3Transfer struct {
method string
- query string // the whole raw query, as issued
- signed []string // the signed header names besides host
+ query string // the whole raw query, as issued
+ signed []string // the signed header names besides host
+ values map[string]string // each signed header's signed value
signature string
}
@@ -68,21 +69,33 @@ type s3Request struct {
}
// s3Server is an httptest S3 for one execution. It answers only the
-// transfers it presigned: the exact query (as decoded multisets), an
-// unexpired grant (403 at or after the expiry on its clock), and every
-// signed header present with its signed value. GET honours If-Match
-// (412) and Range (206 from "bytes=N-", 416 past the end); PUT honours
-// If-None-Match: * (412 when the key exists). Knobs, set before the
-// requests they affect:
+// transfers it presigned: the exact query (as decoded multisets), every
+// signed header present with exactly its signed value (else 403, as a
+// signature mismatch), and an unexpired grant (403 at or after the expiry
+// on its clock). GET honours If-Match (412) and Range (206 from
+// "bytes=N-", 416 past the end); PUT honours If-None-Match: * (412 when
+// the key exists). Breaches of the presigned contract are recorded for
+// Problems and CheckClean. Knobs, set before the requests they affect:
//
// - Cuts: absolute offsets of the source; each GET whose body would
// pass the first remaining cut sends up to it and drops the
// connection, and the cut is used up.
+// - StallAt: an absolute offset; the GET whose body would pass it sends
+// up to it, closes Stalled, and then sends nothing until the client
+// goes away. Used once.
// - Chunked: GETs send no Content-Length.
-// - HoldBody: a 200 GET sends its headers, then sends nothing until the
+// - CloseDelimited: a 200 sends neither Content-Length nor chunked
+// framing, then nothing until the client goes away.
+// - HoldGet: GET number n sends its headers, then nothing until the
// client goes away.
-// - IgnoreRange, SkewRange, NoTotal, TotalLie: a store that answers a resume
-// wrongly.
+// - A store that answers wrongly: IgnoreIfMatch (serves the current
+// object whatever If-Match says), NoETag, PartialFirst (a 206 to a GET
+// with no Range), IgnoreRange (a 200 to a resume), SkewRange (a 206
+// from this many bytes later), NoTotal (a "*" total), TotalLie (added
+// to a 206's total; below 0, a consistent 206 of an object that much
+// shorter), ShortRange (a 206 of only this many bytes), TrimBody (a
+// 206 body this many bytes short of its Content-Range; chunked only),
+// LengthLie (added to the next 206's Content-Length, once).
// - OnGet(n): runs before GET number n (from 1) is served; a non-zero
// answer is sent as the status, with no body (a 3xx with a Location
// on this server), and dropConnection closes the connection before
@@ -100,19 +113,28 @@ type s3Server struct {
problems []string
gets int
- Cuts []int64
- Chunked bool
- HoldBody bool
- IgnoreRange bool // answer a ranged GET with the whole object, 200
- SkewRange int64 // answer a ranged GET from this many bytes later
- NoTotal bool // a 206's Content-Range total is "*"
- TotalLie int64 // add this to a 206's Content-Range total; below 0, the 206 is of an object that much shorter
- OnGet func(n int) int
+ Cuts []int64
+ StallAt int64
+ Stalled chan struct{}
+ Chunked bool
+ CloseDelimited bool
+ HoldGet int
+ IgnoreIfMatch bool
+ NoETag bool
+ PartialFirst bool
+ IgnoreRange bool
+ SkewRange int64
+ NoTotal bool
+ TotalLie int64
+ ShortRange int64
+ TrimBody int64
+ LengthLie int64
+ OnGet func(n int) int
}
// newS3 starts a server whose grant expires an hour after clock's now.
func newS3(t *testing.T, clock *testClock) *s3Server {
- s := &s3Server{t: t, clock: clock, expiry: clock.Now().Add(time.Hour), objects: map[string]*s3Object{}, transfers: map[string]s3Transfer{}}
+ s := &s3Server{t: t, clock: clock, expiry: clock.Now().Add(time.Hour), objects: map[string]*s3Object{}, transfers: map[string]s3Transfer{}, Stalled: make(chan struct{})}
s.srv = httptest.NewServer(http.HandlerFunc(s.serve))
t.Cleanup(s.srv.Close)
return s
@@ -134,7 +156,11 @@ func (s *s3Server) payload(t *testing.T, preset string, data []byte, limit int64
defer s.mu.Unlock()
s.objects[srcPath] = &s3Object{data: data, etag: testETag}
tr := media.Transfers{OutPrefix: s.srv.URL + outPrefix}
- presign := func(method, path, xid string, signed []string) (base, rest string) {
+ presign := func(method, path, xid string, values map[string]string) (base, rest string) {
+ var signed []string
+ for k := range values {
+ signed = append(signed, k)
+ }
sig := make([]byte, 32)
if _, err := rand.Read(sig); err != nil {
t.Fatal(err)
@@ -158,16 +184,16 @@ func (s *s3Server) payload(t *testing.T, preset string, data []byte, limit int64
if tr.Shared == "" {
tr.Shared = shared
}
- s.transfers[path] = s3Transfer{method: method, query: q, signed: signed, signature: sigHex}
+ s.transfers[path] = s3Transfer{method: method, query: q, signed: signed, values: values, signature: sigHex}
return b, rest
}
- base, rest := presign("GET", srcPath, "GetObject", []string{"if-match"})
+ base, rest := presign("GET", srcPath, "GetObject", map[string]string{"if-match": `"` + testETag + `"`})
tr.Source = media.Transfer{URL: base, Method: "GET", Query: rest, Header: map[string]string{"If-Match": `"` + testETag + `"`}}
for _, name := range media.OutputNames(preset) {
- _, rest := presign("PUT", outPrefix+name, "PutObject", []string{"content-type", "if-none-match"})
+ _, rest := presign("PUT", outPrefix+name, "PutObject", map[string]string{"content-type": media.ContentType(name), "if-none-match": "*"})
tr.Outputs = append(tr.Outputs, media.Transfer{Name: name, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": media.ContentType(name), "If-None-Match": "*"}})
}
- base, rest = presign("PUT", resultPath, "PutObject", []string{"content-type", "if-none-match"})
+ base, rest = presign("PUT", resultPath, "PutObject", map[string]string{"content-type": "application/json", "if-none-match": "*"})
tr.Result = media.Transfer{URL: base, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}}
return media.Payload{
V: media.PayloadVersion, Execution: testExec, Preset: preset,
@@ -198,6 +224,13 @@ func (s *s3Server) Requests() []s3Request {
return append([]s3Request(nil), s.requests...)
}
+// Problems are the breaches of the presigned contract so far.
+func (s *s3Server) Problems() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]string(nil), s.problems...)
+}
+
// CheckClean fails t if any request broke the presigned contract.
func (s *s3Server) CheckClean(t *testing.T) {
t.Helper()
@@ -254,8 +287,8 @@ func (s *s3Server) decide(r *http.Request, forced int) (int, func(http.ResponseW
return http.StatusForbidden, nil
}
for _, name := range tr.signed {
- if r.Header.Get(name) == "" {
- s.problems = append(s.problems, r.Method+" without its signed "+name)
+ if got := r.Header.Values(name); len(got) != 1 || got[0] != tr.values[name] {
+ s.problems = append(s.problems, r.Method+" without its signed "+name+" value")
return http.StatusForbidden, nil
}
}
@@ -276,7 +309,7 @@ func (s *s3Server) get(r *http.Request) (int, func(http.ResponseWriter)) {
if !ok {
return http.StatusNotFound, nil
}
- if r.Header.Get("If-Match") != `"`+obj.etag+`"` {
+ if !s.IgnoreIfMatch && r.Header.Get("If-Match") != `"`+obj.etag+`"` {
return http.StatusPreconditionFailed, nil
}
size := int64(len(obj.data))
@@ -293,51 +326,109 @@ func (s *s3Server) get(r *http.Request) (int, func(http.ResponseWriter)) {
return http.StatusRequestedRangeNotSatisfiable, nil
}
start, status = min(n+s.SkewRange, size-1), http.StatusPartialContent
+ } else if rg == "" && s.PartialFirst {
+ status = http.StatusPartialContent
}
- if status == http.StatusPartialContent && s.TotalLie < 0 {
- size += s.TotalLie // a consistent answer for a smaller object
+ last := size // the range's exclusive end
+ length := size - start
+ if status == http.StatusPartialContent {
+ if s.TotalLie < 0 {
+ size += s.TotalLie
+ last = size
+ }
+ if s.ShortRange > 0 {
+ last = min(start+s.ShortRange, size)
+ }
+ length = last - start
+ }
+ declared := length
+ send := last // the exclusive end of the bytes sent
+ if status == http.StatusPartialContent {
+ declared += s.LengthLie
+ s.LengthLie = 0
+ if s.TrimBody > 0 {
+ send -= s.TrimBody
+ }
}
- end := size
- cut := false
- if len(s.Cuts) > 0 && s.Cuts[0] > start && s.Cuts[0] < size {
- end, cut = s.Cuts[0], true
+ cut, stall := false, false
+ if len(s.Cuts) > 0 && s.Cuts[0] > start && s.Cuts[0] < send {
+ send, cut = s.Cuts[0], true
s.Cuts = s.Cuts[1:]
}
- body := obj.data[start:end]
+ if s.StallAt > start && s.StallAt < send {
+ send, stall, cut = s.StallAt, true, false
+ s.StallAt = 0
+ }
+ body := obj.data[start:send]
total := strconv.FormatInt(size+max(s.TotalLie, 0), 10)
if s.NoTotal {
total = "*"
}
- chunked, hold, enc, etag := s.Chunked, s.HoldBody && status == http.StatusOK, obj.encoding, obj.etag
+ contentRange := "bytes " + strconv.FormatInt(start, 10) + "-" + strconv.FormatInt(last-1, 10) + "/" + total
+ hold := s.HoldGet == s.gets
+ closeDelimited := s.CloseDelimited && status == http.StatusOK
+ chunked, enc, etag, noETag, stalled := s.Chunked, obj.encoding, obj.etag, s.NoETag, s.Stalled
return status, func(w http.ResponseWriter) {
+ if closeDelimited {
+ holdUnframed(w, etag, r)
+ return
+ }
h := w.Header()
- h.Set("ETag", `"`+etag+`"`)
+ if !noETag {
+ h.Set("ETag", `"`+etag+`"`)
+ }
if enc != "" {
h.Set("Content-Encoding", enc)
}
if !chunked {
- h.Set("Content-Length", strconv.FormatInt(size-start, 10))
+ h.Set("Content-Length", strconv.FormatInt(declared, 10))
}
if status == http.StatusPartialContent {
- h.Set("Content-Range", "bytes "+strconv.FormatInt(start, 10)+"-"+strconv.FormatInt(size-1, 10)+"/"+total)
+ h.Set("Content-Range", contentRange)
}
w.WriteHeader(status)
if hold {
w.(http.Flusher).Flush()
- select {
- case <-r.Context().Done():
- case <-time.After(10 * time.Second):
- }
+ waitGone(r)
panic(http.ErrAbortHandler)
}
w.Write(body)
- if cut {
+ switch {
+ case stall:
+ w.(http.Flusher).Flush()
+ close(stalled)
+ waitGone(r)
+ panic(http.ErrAbortHandler)
+ case cut:
w.(http.Flusher).Flush()
panic(http.ErrAbortHandler)
}
}
}
+// waitGone returns when the client has gone, or after 30 s.
+func waitGone(r *http.Request) {
+ select {
+ case <-r.Context().Done():
+ case <-time.After(30 * time.Second):
+ }
+}
+
+// holdUnframed answers 200 with no Content-Length and no chunked framing
+// (a body the connection's close would end), then sends nothing until
+// the client goes away.
+func holdUnframed(w http.ResponseWriter, etag string, r *http.Request) {
+ conn, rw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ panic(err)
+ }
+ defer conn.Close()
+ rw.WriteString("HTTP/1.1 200 OK\r\nETag: \"" + etag + "\"\r\nConnection: close\r\n\r\n")
+ rw.Flush()
+ conn.SetReadDeadline(time.Now().Add(30 * time.Second))
+ io.Copy(io.Discard, conn)
+}
+
func (s *s3Server) put(r *http.Request) (int, func(http.ResponseWriter)) {
path := r.URL.EscapedPath()
if _, exists := s.objects[path]; exists && r.Header.Get("If-None-Match") == "*" {