Skip to content

Commit 47ed4b4

Browse files
authored
Merge pull request #649 from simonchrz/fix/truncated-upstream-metadata
Fail metadata reads when upstream cuts a document off
2 parents 83a0822 + 358b135 commit 47ed4b4

4 files changed

Lines changed: 170 additions & 2 deletions

File tree

‎internal/handler/handler.go‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,9 @@ func (p *Proxy) ReadMetadata(r io.Reader) ([]byte, error) {
157157
// Reading into a buffer of that size avoids io.ReadAll growing its buffer
158158
// step by step, which peaks at more than twice the document size. size is
159159
// only a hint: a negative one, or one above the limit, reads as ReadMetadata
160-
// does, and a body of a different length is still read correctly.
160+
// does, and a body of a different length is still read correctly. A body
161+
// read through upstreamBodyReader that upstream cuts off fails, even though
162+
// it ends like a body shorter than size.
161163
func (p *Proxy) ReadMetadataSized(r io.Reader, size int64) ([]byte, error) {
162164
limit := p.MetadataMaxSize
163165
if limit <= 0 {
@@ -170,7 +172,10 @@ func (p *Proxy) ReadMetadataSized(r io.Reader, size int64) ([]byte, error) {
170172
// the buffer and a longer one is noticed.
171173
buf := make([]byte, size+1)
172174
n, err := io.ReadFull(r, buf)
175+
var cut *upstreamBodyError
173176
switch {
177+
case errors.As(err, &cut):
178+
return nil, err
174179
case errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF):
175180
if int64(n) < size/2 {
176181
// The hint was far off; don't keep the oversized buffer alive.
@@ -2010,7 +2015,7 @@ func (p *Proxy) fetchUpstreamMetadata(ctx context.Context, upstreamURL string, e
20102015

20112016
// ContentLength is -1 when the transport decompresses the body, and
20122017
// otherwise the length of the bytes read here.
2013-
body, err := p.ReadMetadataSized(resp.Body, resp.ContentLength)
2018+
body, err := p.ReadMetadataSized(upstreamBodyReader{resp.Body}, resp.ContentLength)
20142019
if err != nil {
20152020
return nil, fmt.Errorf("reading response: %w", err)
20162021
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package handler
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"strings"
9+
"sync"
10+
"testing"
11+
12+
"github.com/git-pkgs/cooldown"
13+
)
14+
15+
// cutMetadataUpstream serves one npm packument and, when cut is set, closes
16+
// the connection halfway through the document it announced.
17+
type cutMetadataUpstream struct {
18+
*httptest.Server
19+
mu sync.Mutex
20+
body string
21+
cut bool
22+
}
23+
24+
func newCutMetadataUpstream(t *testing.T, body string) *cutMetadataUpstream {
25+
t.Helper()
26+
u := &cutMetadataUpstream{body: body}
27+
u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
28+
u.mu.Lock()
29+
body, cut := u.body, u.cut
30+
u.mu.Unlock()
31+
if r.URL.Path != "/pkg" {
32+
http.NotFound(w, r)
33+
return
34+
}
35+
w.Header().Set("Content-Type", "application/json")
36+
w.Header().Set("Content-Length", fmt.Sprint(len(body)))
37+
if cut {
38+
_, _ = io.WriteString(w, body[:len(body)/2])
39+
return
40+
}
41+
_, _ = io.WriteString(w, body)
42+
}))
43+
t.Cleanup(u.Close)
44+
return u
45+
}
46+
47+
func (u *cutMetadataUpstream) set(body string, cut bool) {
48+
u.mu.Lock()
49+
defer u.mu.Unlock()
50+
u.body, u.cut = body, cut
51+
}
52+
53+
// truncPackument is an npm packument with n versions published long ago.
54+
func truncPackument(n int) string {
55+
var versions, times []string
56+
for i := range n {
57+
v := fmt.Sprintf("1.0.%d", i)
58+
versions = append(versions, fmt.Sprintf(`%q:{"name":"pkg","version":%q,"dist":{"tarball":"https://registry.npmjs.org/pkg/-/pkg-%s.tgz"}}`, v, v, v))
59+
times = append(times, fmt.Sprintf(`%q:"2020-01-01T00:00:00Z"`, v))
60+
}
61+
return `{"name":"pkg","dist-tags":{"latest":"1.0.0"},"versions":{` + strings.Join(versions, ",") +
62+
`},"time":{` + strings.Join(times, ",") + `}}`
63+
}
64+
65+
// TestMetadataTruncatedUpstream checks that a document upstream cuts off
66+
// before its Content-Length is neither served nor cached: the cached copy is
67+
// served instead, with and without cooldown.
68+
func TestMetadataTruncatedUpstream(t *testing.T) {
69+
for _, withCooldown := range []bool{false, true} {
70+
t.Run(map[bool]string{false: "no cooldown", true: "cooldown"}[withCooldown], func(t *testing.T) {
71+
u := newCutMetadataUpstream(t, truncPackument(50))
72+
proxy, db, _, _ := setupTestProxy(t)
73+
proxy.HTTPClient = u.Client()
74+
proxy.CacheMetadata = true
75+
if withCooldown {
76+
proxy.Cooldown = &cooldown.Config{Default: "3d"}
77+
}
78+
handler := NewNPMHandler(proxy, "http://proxy.example", u.URL).Routes()
79+
80+
first := serve(handler, "/pkg", nil)
81+
if first.Code != http.StatusOK {
82+
t.Fatalf("first request: status %d", first.Code)
83+
}
84+
before, err := db.GetMetadataCache("npm", "pkg")
85+
if err != nil || before == nil {
86+
t.Fatalf("no metadata row after the first request: %v", err)
87+
}
88+
89+
u.set(truncPackument(51), true)
90+
expireMetadata(t, db, "npm", "pkg")
91+
proxy.SetMetadataRewriteCacheSize(0)
92+
93+
rec := serve(handler, "/pkg", nil)
94+
if rec.Code != http.StatusOK || rec.Body.String() != first.Body.String() {
95+
t.Errorf("status %d, want 200 with the cached document", rec.Code)
96+
}
97+
after, err := db.GetMetadataCache("npm", "pkg")
98+
if err != nil || after == nil || after.ContentDigest != before.ContentDigest {
99+
t.Error("the cut-off document replaced the cached copy")
100+
}
101+
})
102+
}
103+
}
104+
105+
// TestMetadataTruncatedUpstreamUncached checks that a cut-off document with
106+
// nothing cached fails the request and is not cached.
107+
func TestMetadataTruncatedUpstreamUncached(t *testing.T) {
108+
u := newCutMetadataUpstream(t, truncPackument(50))
109+
u.set(truncPackument(50), true)
110+
proxy, db, _, _ := setupTestProxy(t)
111+
proxy.HTTPClient = u.Client()
112+
proxy.CacheMetadata = true
113+
handler := NewNPMHandler(proxy, "http://proxy.example", u.URL).Routes()
114+
115+
if rec := serve(handler, "/pkg", nil); rec.Code != http.StatusBadGateway {
116+
t.Errorf("status %d, want 502", rec.Code)
117+
}
118+
if entry, _ := db.GetMetadataCache("npm", "pkg"); entry != nil {
119+
t.Error("cached the cut-off document")
120+
}
121+
}

‎internal/handler/read_metadata_test.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"io"
88
"runtime"
9+
"strings"
910
"testing"
1011
"testing/iotest"
1112
)
@@ -131,3 +132,18 @@ func TestReadMetadataSizedAllocatesOnce(t *testing.T) {
131132
t.Errorf("allocated %d bytes reading %d", allocated, size)
132133
}
133134
}
135+
136+
// TestReadMetadataSizedTruncatedUpstream checks that an upstream body cut
137+
// off before its Content-Length fails, while a body shorter than a size
138+
// hint is still read.
139+
func TestReadMetadataSizedTruncatedUpstream(t *testing.T) {
140+
p := &Proxy{}
141+
cut := io.MultiReader(strings.NewReader(`{"name":`), iotest.ErrReader(io.ErrUnexpectedEOF))
142+
if _, err := p.ReadMetadataSized(upstreamBodyReader{cut}, 100); !errors.Is(err, io.ErrUnexpectedEOF) {
143+
t.Errorf("cut off body: error %v, want io.ErrUnexpectedEOF", err)
144+
}
145+
got, err := p.ReadMetadataSized(strings.NewReader(`{"name":"x"}`), 100)
146+
if err != nil || string(got) != `{"name":"x"}` {
147+
t.Errorf("short body = %q, %v", got, err)
148+
}
149+
}

‎internal/handler/upstream_body.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package handler
2+
3+
import (
4+
"errors"
5+
"io"
6+
)
7+
8+
// upstreamBodyReader marks a failure to read a document from upstream, so a
9+
// body upstream cuts off is told apart from one that ends, and from a
10+
// failure to store it.
11+
type upstreamBodyReader struct{ r io.Reader }
12+
13+
func (u upstreamBodyReader) Read(b []byte) (int, error) {
14+
n, err := u.r.Read(b)
15+
if err != nil && !errors.Is(err, io.EOF) {
16+
err = &upstreamBodyError{err}
17+
}
18+
return n, err
19+
}
20+
21+
// upstreamBodyError is a failure to read a document from upstream. It is
22+
// handled as an upstream failure: the stored copy, if any, is served.
23+
type upstreamBodyError struct{ err error }
24+
25+
func (e *upstreamBodyError) Error() string { return "reading upstream metadata: " + e.err.Error() }
26+
func (e *upstreamBodyError) Unwrap() error { return e.err }

0 commit comments

Comments
 (0)