carlos / platform Public

media: image reads follow storage redirects without credentials

Astra's re-review: refusing every cross-origin redirect also refused the
HTTPS redirects to presigned storage that OCI registries may send.

A GET or HEAD may now follow HTTPS redirects, without the registry's
authorization, userinfo or a Referer. Once a read leaves the registry it
stays unauthenticated, even on a hop back. Every hop is checked, the limit
stays at ten, and http is refused except between loopback addresses for a
loopback registry. POST, PATCH and PUT stay on the registry's origin.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a492692e9e141cb7f496ba8d9dc55c0c046f490a parent add7bc3
3 files changed, +239 −17
  • cmd/mediaimage/mediaimage_test.go +195 −3
  • cmd/mediaimage/oci.go +43 −13
  • docs/superpowers/notes/media-conversion-copy-deck.md +1 −1

CI failed — run details

diff --git a/cmd/mediaimage/mediaimage_test.go b/cmd/mediaimage/mediaimage_test.go
index 0274fea8d..0a4377f28 100644
--- a/cmd/mediaimage/mediaimage_test.go
+++ b/cmd/mediaimage/mediaimage_test.go
@@ -670,7 +670,7 @@ type fakeRegistry struct {
password string
tamper bool
failDigest bool // a manifest read by digest answers 500
- redirect string // every request is sent here instead
+ redirect string // every POST, PATCH and PUT is sent here instead
location func(stage string) string // replaces an upload's Location
srv *httptest.Server
}
@@ -695,7 +695,7 @@ func (r *fakeRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
}
- if r.redirect != "" {
+ if r.redirect != "" && req.Method != http.MethodGet && req.Method != http.MethodHead {
w.Header().Set("Location", r.redirect)
w.WriteHeader(http.StatusTemporaryRedirect)
return
@@ -1968,7 +1968,7 @@ func TestPushKeepsCredentialsOnTheRegistry(t *testing.T) {
"no location": func(reg *fakeRegistry) {
reg.location = func(string) string { return "" }
},
- "a redirect elsewhere": func(reg *fakeRegistry) { reg.redirect = trap.URL + "/stolen" },
+ "an upload redirected elsewhere": func(reg *fakeRegistry) { reg.redirect = trap.URL + "/stolen" },
} {
t.Run(name, func(t *testing.T) {
reg := newFakeRegistry(t)
@@ -2017,6 +2017,198 @@ func TestUploadRefusesADowngradeToHTTP(t *testing.T) {
}
}
+// hop is one fake HTTPS server in a redirect chain. It records what each
+// request brought and answers with next, or 200 when next is empty.
+type hop struct {
+ srv *httptest.Server
+ mu sync.Mutex
+ auth []string
+ refs []string
+ seen []string
+ next func(path string) string
+}
+
+func newHop(t *testing.T) *hop {
+ t.Helper()
+ h := &hop{}
+ h.srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ h.mu.Lock()
+ h.auth = append(h.auth, req.Header.Get("Authorization"))
+ h.refs = append(h.refs, req.Referer())
+ h.seen = append(h.seen, req.Method+" "+req.URL.Path)
+ next := h.next
+ h.mu.Unlock()
+ if next != nil {
+ if target := next(req.URL.Path); target != "" {
+ w.Header().Set("Location", target)
+ w.WriteHeader(http.StatusTemporaryRedirect)
+ return
+ }
+ }
+ _, _ = w.Write([]byte("stored"))
+ }))
+ t.Cleanup(h.srv.Close)
+ return h
+}
+
+// tlsRegistry is a registry client trusting the fake HTTPS servers.
+func tlsRegistry(t *testing.T, h *hop) *registry {
+ t.Helper()
+ saved := httpClient
+ httpClient = h.srv.Client()
+ t.Cleanup(func() { httpClient = saved })
+ return &registry{base: h.srv.URL, repo: "engine", basic: "Basic secret"}
+}
+
+func TestReadFollowsStorageWithoutCredentials(t *testing.T) {
+ for _, method := range []string{http.MethodGet, http.MethodHead} {
+ t.Run(method, func(t *testing.T) {
+ origin, first, second := newHop(t), newHop(t), newHop(t)
+ origin.next = func(string) string { return first.srv.URL + "/presigned" }
+ first.next = func(string) string { return second.srv.URL + "/presigned-again" }
+ reg := tlsRegistry(t, origin)
+ status := 0
+ err := send(t.Context(), reg, method, reg.url("blobs/sha256:abc"), "", nil, 0, func(resp *http.Response) error {
+ status = resp.StatusCode
+ return nil
+ })
+ if err != nil || status != http.StatusOK {
+ t.Fatalf("read = %d, %v", status, err)
+ }
+ if !slices.Equal(origin.auth, []string{"Basic secret"}) {
+ t.Fatalf("the registry saw %q", origin.auth)
+ }
+ if !slices.Equal(first.auth, []string{""}) || !slices.Equal(second.auth, []string{""}) {
+ t.Fatalf("storage saw authorization: %q and %q", first.auth, second.auth)
+ }
+ if !slices.Equal(second.refs, []string{""}) {
+ t.Fatalf("the second hop was told the presigned URL before it: %q", second.refs)
+ }
+ })
+ }
+}
+
+// TestCredentialsNeverComeBack: Go's client would restore the header on a
+// hop that returns to the registry.
+func TestCredentialsNeverComeBack(t *testing.T) {
+ origin, storage := newHop(t), newHop(t)
+ origin.next = func(path string) string {
+ switch path {
+ case "/v2/engine/manifests/x":
+ return origin.srv.URL + "/same-origin"
+ case "/same-origin":
+ return storage.srv.URL + "/presigned"
+ }
+ return ""
+ }
+ storage.next = func(string) string { return origin.srv.URL + "/back" }
+ reg := tlsRegistry(t, origin)
+ data, err := fetchManifest(t.Context(), reg, "x")
+ if err != nil || string(data) != "stored" {
+ t.Fatalf("fetchManifest = %q, %v", data, err)
+ }
+ if want := []string{"Basic secret", "Basic secret", ""}; !slices.Equal(origin.auth, want) {
+ t.Fatalf("the registry saw %q on %q, want %q", origin.auth, origin.seen, want)
+ }
+ if !slices.Equal(storage.auth, []string{""}) {
+ t.Fatalf("storage saw %q", storage.auth)
+ }
+}
+
+func TestReadRefusesADowngradeToHTTP(t *testing.T) {
+ trap, hits := credentialTrap(t)
+ t.Run("from the registry", func(t *testing.T) {
+ origin := newHop(t)
+ origin.next = func(string) string { return trap.URL + "/plain" }
+ reg := tlsRegistry(t, origin)
+ if _, err := fetchManifest(t.Context(), reg, "x"); !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("fetchManifest = %v, want errUnsafeLocation", err)
+ }
+ })
+ t.Run("from storage", func(t *testing.T) {
+ origin, storage := newHop(t), newHop(t)
+ origin.next = func(string) string { return storage.srv.URL + "/presigned" }
+ storage.next = func(string) string { return trap.URL + "/plain" }
+ reg := tlsRegistry(t, origin)
+ if _, err := fetchManifest(t.Context(), reg, "x"); !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("fetchManifest = %v, want errUnsafeLocation", err)
+ }
+ })
+ if got := hits.Load(); got != 0 {
+ t.Fatalf("the plain http server got %d requests", got)
+ }
+}
+
+func TestUploadsStayOnTheRegistry(t *testing.T) {
+ for _, method := range []string{http.MethodPost, http.MethodPatch, http.MethodPut} {
+ t.Run(method, func(t *testing.T) {
+ origin, storage := newHop(t), newHop(t)
+ origin.next = func(string) string { return storage.srv.URL + "/elsewhere" }
+ reg := tlsRegistry(t, origin)
+ body := []byte("manifest")
+ err := send(t.Context(), reg, method, reg.url("manifests/v1"), mediaTypeOCIManifest, bytes.NewReader(body), int64(len(body)), expect("write", http.StatusCreated))
+ if !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("send = %v, want errUnsafeLocation", err)
+ }
+ if len(storage.seen) != 0 {
+ t.Fatalf("storage saw %q", storage.seen)
+ }
+ })
+ }
+ t.Run("a POST that a 303 turns into a GET", func(t *testing.T) {
+ reg := &registry{base: "https://registry.example"}
+ next, err := http.NewRequest(http.MethodGet, "https://storage.example/x", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first, err := http.NewRequest(http.MethodPost, "https://registry.example/v2/x", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.checkRedirect(next, []*http.Request{first}); !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("checkRedirect = %v, want errUnsafeLocation", err)
+ }
+ })
+}
+
+func TestCheckRedirectRules(t *testing.T) {
+ request := func(method, target string) *http.Request {
+ req, err := http.NewRequest(method, target, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return req
+ }
+ first := request(http.MethodGet, "https://registry.example/v2/x")
+ limit := slices.Repeat([]*http.Request{first}, maxRedirects)
+ for name, c := range map[string]struct {
+ base, target string
+ via []*http.Request
+ ok bool
+ }{
+ "https storage": {"https://registry.example", "https://storage.example/x", []*http.Request{first}, true},
+ "the last hop within the limit": {"https://registry.example", "https://storage.example/x", limit[1:], true},
+ "past the limit": {"https://registry.example", "https://storage.example/x", limit, false},
+ "storage with userinfo": {"https://registry.example", "https://u:p@storage.example/x", []*http.Request{first}, false},
+ "http on the registry's host": {"https://registry.example", "http://registry.example/x", []*http.Request{first}, false},
+ "http loopback from https": {"https://registry.example", "http://127.0.0.1/x", []*http.Request{first}, false},
+ "http remote from loopback": {"http://127.0.0.1:5000", "http://storage.example/x", []*http.Request{request(http.MethodGet, "http://127.0.0.1:5000/v2/x")}, false},
+ "http loopback from loopback": {"http://127.0.0.1:5000", "http://127.0.0.1:6000/x", []*http.Request{request(http.MethodGet, "http://127.0.0.1:5000/v2/x")}, true},
+ "another scheme": {"https://registry.example", "ftp://storage.example/x", []*http.Request{first}, false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ reg := &registry{base: c.base}
+ err := reg.checkRedirect(request(http.MethodGet, c.target), c.via)
+ if c.ok && err != nil {
+ t.Fatalf("refused: %v", err)
+ }
+ if !c.ok && !errors.Is(err, errUnsafeLocation) {
+ t.Fatalf("checkRedirect = %v, want errUnsafeLocation", err)
+ }
+ })
+ }
+}
+
func TestCheckOrigin(t *testing.T) {
reg := &registry{base: "https://registry.example"}
for target, ok := range map[string]bool{
diff --git a/cmd/mediaimage/oci.go b/cmd/mediaimage/oci.go
index 7178e3505..5581784db 100644
--- a/cmd/mediaimage/oci.go
+++ b/cmd/mediaimage/oci.go
@@ -33,6 +33,7 @@ const (
// transfer included.
requestTimeout = 30 * time.Minute
retryAttempts = 5
+ maxRedirects = 10
)
var (
@@ -316,23 +317,52 @@ func (r *registry) checkOrigin(u *url.URL) error {
return nil
}
-// do sends a request. With credentials, every request and every redirect
-// stays on the configured registry. An anonymous GET answered 401 fetches
-// the token the challenge names and is sent once more.
+// readTransport reports whether a redirected read may use this URL's
+// scheme: https, or http only between a loopback registry and loopback.
+func (r *registry) readTransport(u *url.URL) bool {
+ if strings.EqualFold(u.Scheme, "https") {
+ return true
+ }
+ return strings.EqualFold(u.Scheme, "http") && strings.HasPrefix(r.base, "http://") && isLoopback(u.Host)
+}
+
+// checkRedirect is the rule for every hop of a registry request. An upload
+// stays on the registry. A read may go on to storage, as OCI registries
+// send blobs to presigned URLs, but it goes without the registry's
+// authorization. Once a read has left the registry it stays unauthenticated,
+// even on a hop back: Go's client would otherwise restore the header there.
+func (r *registry) checkRedirect(next *http.Request, via []*http.Request) error {
+ if len(via) >= maxRedirects {
+ return fmt.Errorf("%w: more than %d redirects", errUnsafeLocation, maxRedirects)
+ }
+ if method := via[0].Method; method != http.MethodGet && method != http.MethodHead {
+ return r.checkOrigin(next.URL)
+ }
+ if next.URL.User != nil || !r.readTransport(next.URL) {
+ return fmt.Errorf("%w: %s://%s", errUnsafeLocation, next.URL.Scheme, next.URL.Hostname())
+ }
+ left := r.checkOrigin(next.URL) != nil
+ for _, hop := range via {
+ left = left || r.checkOrigin(hop.URL) != nil
+ }
+ if left {
+ next.Header.Del("Authorization")
+ next.Header.Del("Referer") // the last hop's URL may be presigned
+ }
+ return nil
+}
+
+// do sends a request. A request with credentials starts on the configured
+// registry, and checkRedirect rules every hop after that. An anonymous GET
+// answered 401 fetches the token the challenge names and is sent once more.
func (r *registry) do(req *http.Request) (*http.Response, error) {
- client := httpClient
+ guarded := *httpClient
+ guarded.CheckRedirect = r.checkRedirect
+ client := &guarded
if r.basic != "" {
if err := r.checkOrigin(req.URL); err != nil {
return nil, err
}
- guarded := *httpClient
- guarded.CheckRedirect = func(next *http.Request, via []*http.Request) error {
- if len(via) >= 10 {
- return errors.New("too many redirects")
- }
- return r.checkOrigin(next.URL)
- }
- client = &guarded
req.Header.Set("Authorization", r.basic)
} else if r.bearer != "" {
req.Header.Set("Authorization", "Bearer "+r.bearer)
@@ -350,7 +380,7 @@ func (r *registry) do(req *http.Request) (*http.Response, error) {
r.bearer = token
retry := req.Clone(req.Context())
retry.Header.Set("Authorization", "Bearer "+token)
- return httpClient.Do(retry)
+ return client.Do(retry)
}
var challengeParam = regexp.MustCompile(`([a-z]+)="([^"]*)"`)
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index c362cbba8..a6199c9b7 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -619,7 +619,7 @@ Operator-facing text from `cmd/mediaimage`, which builds and pushes the engine i
| `image.release.index` | `sha256 mismatch: %s %s is not the file its release names` (pending Luna pass; plan 3 Task 8) |
| `image.privileged` | `setuid or setgid path in the image: %s`, the paths joined by `, ` (pending Luna pass; plan 3 Task 8) |
| `image.toolchain` | `wrong Go toolchain: mediaimage runs on %s, releases use %s`; `wrong Go toolchain: %s was built with %s, releases use %s`; `wrong Go toolchain: %s names no Go version: %s` (pending Luna pass; plan 3 Task 8) |
-| `image.location` | `the registry pointed outside itself: %s://%s`; `the registry pointed outside itself: an upload answer has no Location`; `the registry pointed outside itself: an upload Location does not parse` (pending Luna pass; plan 3 Task 8) |
+| `image.location` | `the registry pointed outside itself: %s://%s`; `the registry pointed outside itself: an upload answer has no Location`; `the registry pointed outside itself: an upload Location does not parse`; `the registry pointed outside itself: more than %d redirects` (pending Luna pass; plan 3 Task 8) |
| `image.push.refused` | `push refused: CARLOS_REGISTRY_PASSWORD is not set`; `push refused: --tag must be a release tag`; `push refused: --repo must be <registry>/<repo>`; `push refused: the layout holds %d manifests` (pending Luna pass; plan 3 Task 8) |
| `image.push.tag` | `tag already holds another image: %s is %s, this image is %s` (pending Luna pass; plan 3 Task 8) |
| `image.push.digest` | `the registry holds a different image: %s after the push, want %s` (pending Luna pass; plan 3 Task 8) |