From 1bf52555aafa7a69418142e1c554fdc6c62a7be1 Mon Sep 17 00:00:00 2001 From: riad Date: Mon, 16 Nov 2026 16:30:36 +0000 Subject: [PATCH 1/6] feat(agent)!: scope plain HTTP to the listed registries (MK8S-451) --plain-http marked every registry insecure, so go-containerregistry raced HTTPS and HTTP for all of them: a registry serving HTTPS no longer failed on a bad certificate, and anyone on the path could answer the HTTP attempt. It also excluded --ca-file, leaving a site with one plain HTTP registry and one signed by a private CA with no working setting. Replace it on the agent with --plain-http-registry=, repeatable. Only a source whose registry matches an entry exactly is marked insecure; every other registry stays HTTPS only. Entries are validated and normalized at startup and logged with a warning. The list goes with --ca-file and still excludes --insecure-skip-tls-verify. Marking a registry is not the only way the library reaches for HTTP: it also races HTTP on its own for a private or loopback IP address and for a localhost name, whatever the list says, and nothing turns that off. Every pull therefore goes through a transport that refuses a plain HTTP request to an unlisted registry before it leaves, so only the HTTPS attempt is left and a bad certificate fails the pull again. Without it, a registry on a private address, the usual case on premises, would be reached over plain HTTP listed or not. imagecachectl import keeps its --plain-http switch, now scoped to the registry of its single source, and goes through the same transport. BREAKING CHANGE: the agent no longer accepts --plain-http and refuses to start with it. Pass --plain-http-registry with the registry the ImageCache sources name instead. A plain HTTP registry on a private or loopback IP address or a localhost name, which the library used to reach over HTTP unlisted, must now be listed too, and imagecachectl import needs --plain-http for it. --- README.md | 5 +- agent/DESIGN.md | 37 +++-- agent/README.md | 20 ++- agent/cmd/manager/main.go | 34 +++- agent/internal/cli/cli.go | 21 ++- agent/internal/cli/cli_test.go | 45 +++++- agent/internal/puller/puller.go | 110 ++++++++++--- agent/internal/puller/puller_test.go | 225 +++++++++++++++++++++++---- agent/test/e2e/e2e_test.go | 27 ++-- 9 files changed, 433 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 1ba332d..864a97a 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,10 @@ by a private CA, on top of the system ones. It is checked on every run, and never read for an archive. `--insecure-skip-tls-verify` accepts any certificate instead, for a test cluster only, and prints a warning. `--plain-http` reaches a registry that serves plain HTTP, and prints a warning -too. It excludes the two certificate flags. +too. It applies to the registry of the source only, and excludes the two +certificate flags. Without it, the registry is reached over HTTPS only, even +on a private or loopback IP address. The agent takes a list instead, +`--plain-http-registry`, see [agent/README.md](agent/README.md). The import refuses to replace a directory without a sentinel. The command runs as root, so a wrong name or cache path that lands on a directory the store did diff --git a/agent/DESIGN.md b/agent/DESIGN.md index 8020c70..6315fe8 100644 --- a/agent/DESIGN.md +++ b/agent/DESIGN.md @@ -310,15 +310,34 @@ Pulling and extraction use unusable one stops the agent at startup rather than failing every pull. `--insecure-skip-tls-verify` turns verification off for test clusters. It excludes `--ca-file`, so neither setting wins in silence. -- On its own, the library uses plain HTTP only for a loopback or private IP - address, or a `localhost` host name. - `--plain-http` marks every registry insecure (`name.Insecure`). The client - then tries HTTPS first, and also HTTP when HTTPS fails or takes more than - 300ms: the first answer wins, on every pull. So the flag also weakens a - registry that serves HTTPS: a certificate error no longer fails the pull, - and anyone on the path can answer the HTTP attempt (port 80 when the - reference names no port). It is for a registry without TLS, and excludes - both certificate flags rather than mixing the two modes. +- On its own, the library also tries plain HTTP for a loopback or private IP + address, or a `localhost` host name, and nothing turns that off. The agent + hands it a transport that refuses any plain HTTP request to a registry that + is not listed, before the request leaves, so only the HTTPS attempt is left + to answer and a bad certificate fails the pull again. Without it, a registry + on a private address, the usual case on premises, would be reached over + plain HTTP whatever the list says. `imagecachectl import` goes through the + same transport: without `--plain-http` it refuses plain HTTP to such an + address too. + `--plain-http-registry` lists registries, as `host[:port]`, to mark + insecure (`name.Insecure`). For those, the client tries HTTPS first, and + also HTTP when HTTPS fails or takes more than 300ms: the first answer wins, + on every pull. So marking a registry also weakens it if it serves HTTPS: a + certificate error no longer fails the pull, and anyone on the path can + answer the HTTP attempt (port 80 when the reference names no port). That + is why the setting is a list and not a switch: a single global flag would + weaken every HTTPS registry the resources name to serve one plain HTTP + registry. Docker's `insecure-registries` and containerd's `hosts.toml` + scope it the same way. + An entry matches the registry of a parsed reference + (`Context().RegistryStr()`) exactly, after the same normalization, so + `docker.io` matches `index.docker.io`. There is no matching by resolved + address: a registry listed by IP and referenced by name, or listed without + its port, does not match. The list goes with `--ca-file`, which covers the + registries that serve TLS, and excludes `--insecure-skip-tls-verify`, meant + for test clusters only. `imagecachectl import` keeps a `--plain-http` + switch: it pulls one source per run, so the switch already covers that + source's registry alone. The cache images are regular container images (they must remain importable and mountable with `ctr` by provisioning tooling), so an artifact-oriented diff --git a/agent/README.md b/agent/README.md index 3af65ae..8c81191 100644 --- a/agent/README.md +++ b/agent/README.md @@ -152,9 +152,23 @@ On a test cluster set up by hand, `--insecure-skip-tls-verify` accepts any registry certificate instead. The agent logs a warning at startup. It excludes `--ca-file`, and no manifest here sets it: never use it on a real node. -A registry that serves plain HTTP needs `--plain-http`. The agent logs a -warning at startup. It excludes `--ca-file` and `--insecure-skip-tls-verify`, -and no manifest here sets it. +A registry that serves plain HTTP needs `--plain-http-registry=`, +repeated for each one. Only the listed registries may be reached over plain +HTTP: every other one is reached over HTTPS only, and still fails on a bad +certificate. That includes a registry on a private or loopback IP address or +a `localhost` name, which the pull library would otherwise also try over plain +HTTP: list it if it serves plain HTTP. Write each entry as the `ImageCache` +sources name the registry: + +- by the same host, an IP if they use an IP and a name if they use a name; +- with the port they carry, and with no port if they carry none; +- with no scheme and no path: `10.0.0.1:5000`, not `http://10.0.0.1:5000`. + +The match is exact, so an entry written another way does not apply and the +pull fails on `HTTP response to HTTPS client`. The agent logs the list with a +warning at startup. It goes with `--ca-file`, which covers the registries that +serve TLS, but not with `--insecure-skip-tls-verify`. No manifest here sets +it. Leader election is deliberately absent. Every agent converges the node it runs on, so there is nothing to elect a leader for. diff --git a/agent/cmd/manager/main.go b/agent/cmd/manager/main.go index f48feeb..2c20ade 100644 --- a/agent/cmd/manager/main.go +++ b/agent/cmd/manager/main.go @@ -21,6 +21,7 @@ import ( "flag" "os" "path/filepath" + "strings" "time" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) @@ -59,6 +60,18 @@ func init() { // +kubebuilder:scaffold:scheme } +// stringList is a flag that can be repeated, each occurrence adding a value. +type stringList []string + +// String implements flag.Value. +func (l *stringList) String() string { return strings.Join(*l, ",") } + +// Set implements flag.Value. +func (l *stringList) Set(v string) error { + *l = append(*l, v) + return nil +} + // nolint:gocyclo func main() { var metricsAddr string @@ -70,7 +83,8 @@ func main() { var resyncPeriod time.Duration var cachePath string var caFile string - var skipVerify, plainHTTP bool + var skipVerify bool + var plainHTTPRegistries stringList var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") @@ -100,9 +114,10 @@ func main() { "Read once at startup: restart the agent after rotating it.") flag.BoolVar(&skipVerify, "insecure-skip-tls-verify", false, "Accept any registry certificate. For a test cluster set up by hand only.") - flag.BoolVar(&plainHTTP, "plain-http", false, - "Allow plain HTTP to every registry. For a registry without TLS. "+ - "Excludes --ca-file and --insecure-skip-tls-verify.") + flag.Var(&plainHTTPRegistries, "plain-http-registry", + "A registry, as host[:port], the agent may reach over plain HTTP. Repeat it for several. "+ + "It must be written as the sources name it: by IP or by name, with the port they carry. "+ + "Any other registry is reached over HTTPS only. Excludes --insecure-skip-tls-verify.") opts := zap.Options{ Development: true, } @@ -210,7 +225,9 @@ func main() { // Checked before anything starts: an unusable CA would otherwise surface // as a failed pull on every node and every resource. - remote, err := puller.NewRemote(puller.TLS{CAFile: caFile, SkipVerify: skipVerify, PlainHTTP: plainHTTP}) + remote, err := puller.NewRemote(puller.TLS{ + CAFile: caFile, SkipVerify: skipVerify, PlainHTTPRegistries: plainHTTPRegistries, + }) if err != nil { setupLog.Error(err, "unable to set up registry TLS") os.Exit(1) @@ -218,8 +235,11 @@ func main() { if skipVerify { setupLog.Info("WARNING: registry certificates are not verified (--insecure-skip-tls-verify)") } - if plainHTTP { - setupLog.Info("WARNING: registries may be reached over plain HTTP (--plain-http)") + if len(plainHTTPRegistries) > 0 { + // Logged in full: an entry that does not match a source exactly + // shows up as "HTTP response to HTTPS client" on the pull. + setupLog.Info("WARNING: these registries may be reached over plain HTTP (--plain-http-registry)", + "registries", []string(plainHTTPRegistries)) } fw, err := controller.NewFSWatcher(nodeName) diff --git a/agent/internal/cli/cli.go b/agent/internal/cli/cli.go index 2b124ed..8e371ee 100644 --- a/agent/internal/cli/cli.go +++ b/agent/internal/cli/cli.go @@ -12,6 +12,7 @@ import ( "path/filepath" "strings" + imgname "github.com/google/go-containerregistry/pkg/name" "github.com/scality/go-errors" "github.com/spf13/cobra" @@ -80,7 +81,7 @@ func Run(ctx context.Context, args []string, out, errOut io.Writer) int { return errors.New("--insecure-skip-tls-verify and --plain-http exclude each other") } err := do(cmd.Context(), cachePath, name, args[0], - puller.TLS{CAFile: caFile, SkipVerify: skipVerify, PlainHTTP: plainHTTP}, out, errOut) + puller.TLS{CAFile: caFile, SkipVerify: skipVerify}, plainHTTP, out, errOut) // An interrupted run is not a failure to diagnose: the extraction // publishes by rename, so nothing half written is left behind. if errors.Is(err, context.Canceled) { @@ -145,13 +146,14 @@ func validate(name, cachePath string) error { return nil } -func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, out, errOut io.Writer) error { +func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, plainHTTP bool, + out, errOut io.Writer) error { store := cache.Store{} // Before the cache state, so that a CA that cannot be used is reported // on every run, including one that would have found the resource // complete, rather than only on the run that finally needs the registry. - src, err := pullerFor(source, tls) + src, err := pullerFor(source, tls, plainHTTP) if err != nil { return err } @@ -159,7 +161,7 @@ func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, out if tls.SkipVerify { printf(errOut, "imagecachectl: warning: the registry certificate is not verified\n") } - if tls.PlainHTTP { + if plainHTTP { printf(errOut, "imagecachectl: warning: the registry may be reached over plain HTTP\n") } } @@ -216,14 +218,21 @@ func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, out // file rather than coming back with a complaint about a reference. // // The TLS and plain HTTP settings only matter to a registry, so an archive -// never reads them. -func pullerFor(source string, tls puller.TLS) (puller.Puller, error) { +// never reads them. The command pulls one source per run, so plain HTTP is +// allowed to that source's registry: the puller takes a list of registries, +// and this one is the only entry. +func pullerFor(source string, tls puller.TLS, plainHTTP bool) (puller.Puller, error) { switch { case strings.HasPrefix(source, string(os.PathSeparator)), strings.HasPrefix(source, "."), strings.HasSuffix(source, ".tar"): return puller.Tarball{}, nil default: + // A reference that does not parse is reported by the pull, which + // names it as one. + if ref, err := imgname.ParseReference(source); plainHTTP && err == nil { + tls.PlainHTTPRegistries = []string{ref.Context().RegistryStr()} + } return puller.NewRemote(tls) } } diff --git a/agent/internal/cli/cli_test.go b/agent/internal/cli/cli_test.go index c57dd6c..ae0203b 100644 --- a/agent/internal/cli/cli_test.go +++ b/agent/internal/cli/cli_test.go @@ -23,6 +23,7 @@ import ( "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/tarball" "github.com/scality/image-cache/agent/internal/cache" + "github.com/scality/image-cache/agent/internal/puller" ) const ( @@ -49,7 +50,9 @@ func archive(t *testing.T, files map[string][]byte) string { return path } -// served pushes the same shape to an in-memory registry and returns its reference. +// served pushes the same shape to an in-memory registry and returns its +// reference. The registry serves plain HTTP on a loopback address, which the +// command reaches with --plain-http only, as it would any other registry. func served(t *testing.T, files map[string][]byte) string { t.Helper() srv := httptest.NewServer(registry.New()) @@ -96,7 +99,7 @@ func TestImportFromARegistry(t *testing.T) { cacheDir := t.TempDir() ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")}) - code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, ref) + code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http", ref) if code != 0 { t.Fatalf("exit = %d, want 0 (%s)", code, errOut) } @@ -282,7 +285,7 @@ func TestASourceShapedLikeAReferenceIsNotReadFromDisk(t *testing.T) { } t.Chdir(cwd) - code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, ref) + code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http", ref) if code != 0 { t.Fatalf("exit = %d, want 0 (%s)", code, errOut) } @@ -587,7 +590,7 @@ func TestImportFailsWhenALayerCannotBeFetched(t *testing.T) { t.Cleanup(cutting.Close) cacheDir := t.TempDir() - code, out, _ := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, + code, out, _ := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http", strings.TrimPrefix(cutting.URL, "http://")+"/boot-cache/worker:1.0.0") if code != 1 { t.Fatalf("exit = %d, want 1 (stdout %q)", code, out) @@ -632,7 +635,17 @@ func TestCAFileIsNotReadForAnArchive(t *testing.T) { func TestSkippingTLSVerificationIsAnnounced(t *testing.T) { cacheDir := t.TempDir() - ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")}) + // A certificate nothing trusts: only skipping the verification reaches it. + srv := httptest.NewTLSServer(registry.New()) + t.Cleanup(srv.Close) + img, err := crane.Image(map[string][]byte{pauseTarPath: []byte("pause")}) + if err != nil { + t.Fatal(err) + } + ref := strings.TrimPrefix(srv.URL, "https://") + "/boot-cache/worker:1.0.0" + if err := crane.Push(img, ref, crane.WithTransport(srv.Client().Transport)); err != nil { + t.Fatal(err) + } code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--insecure-skip-tls-verify", ref) @@ -698,7 +711,9 @@ func TestImportRecordsTheSameImageWhateverTheSource(t *testing.T) { layers := make([][]string, 0, len(sources)) for _, src := range sources { cacheDir := t.TempDir() - if code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, src); code != 0 { + // An archive reaches no registry, so --plain-http changes nothing for it. + if code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, + "--plain-http", src); code != 0 { t.Fatalf("%s: exit = %d (%s)", src, code, errOut) } r := readSentinel(t, cacheDir) @@ -720,8 +735,8 @@ func TestImportRecordsTheSameImageWhateverTheSource(t *testing.T) { // servedByName is served, but the reference names example.com and the // library default transport sends every address to the server for the rest -// of the test. go-containerregistry already uses plain HTTP for a loopback -// registry, so only a host name shows what --plain-http changes. +// of the test. A host name is the plain case: the library tries nothing but +// HTTPS for it, so the refusal comes from the registry alone. func servedByName(t *testing.T, files map[string][]byte) string { t.Helper() ref := served(t, files) @@ -770,6 +785,20 @@ func TestPlainHTTPReachesARegistryWithoutTLS(t *testing.T) { } } +// The library would race plain HTTP for a loopback registry on its own. The +// command still refuses it without --plain-http, as it would a host name. +func TestPlainHTTPIsNeededForALoopbackRegistry(t *testing.T) { + ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")}) + + code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", t.TempDir(), ref) + if code != 1 { + t.Fatalf("exit = %d without --plain-http, want 1 (%s)", code, errOut) + } + if !strings.Contains(errOut, puller.ErrUnlistedPlainHTTP.Error()) { + t.Errorf("stderr = %s, want the plain HTTP attempt refused", errOut) + } +} + func TestPlainHTTPExcludesTheCertificateFlags(t *testing.T) { ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")}) for _, flags := range [][]string{ diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index af9d0ff..41d20e6 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "os" + "slices" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" @@ -31,6 +32,12 @@ var ( ErrCA = errors.New("unusable registry CA") // ErrTLS covers TLS settings that contradict each other. ErrTLS = errors.New("conflicting registry TLS settings") + // ErrPlainHTTPRegistry covers a plain HTTP registry entry that is not a + // host[:port]. + ErrPlainHTTPRegistry = errors.New("invalid plain HTTP registry") + // ErrUnlistedPlainHTTP covers a plain HTTP request to a registry that is + // not listed, refused before it leaves, see httpsOnly. + ErrUnlistedPlainHTTP = errors.New("plain HTTP to an unlisted registry refused") ) // Image identifies what a source resolved to. @@ -58,12 +65,13 @@ type Puller interface { } // Remote pulls linux/amd64 images from an OCI registry. The zero value -// trusts the system CAs only. +// trusts the system CAs only, and reaches every registry over HTTPS only. type Remote struct { // transport is nil for go-containerregistry's default. transport http.RoundTripper - // plainHTTP marks every registry as insecure, see TLS.PlainHTTP. - plainHTTP bool + // plainHTTP lists the registries marked insecure, normalized as + // name.Registry.RegistryStr returns them, see TLS.PlainHTTPRegistries. + plainHTTP []string } // TLS says how a Remote reaches the registry and checks its certificate. @@ -73,9 +81,14 @@ type TLS struct { // SkipVerify accepts any certificate. It is meant for a test cluster set // up by hand, never for a node. SkipVerify bool - // PlainHTTP lets the pull use plain HTTP. It is for a registry without - // TLS, so it excludes the two certificate settings. - PlainHTTP bool + // PlainHTTPRegistries lists the registries, as host[:port], the pull may + // reach over plain HTTP. Only these are: every other registry stays + // HTTPS only, and keeps failing on a bad certificate. The match is exact, + // so a registry listed by IP and referenced by name, or listed without + // the port its references carry, is not one of them. It goes with + // CAFile, which covers the registries that serve TLS, but not with + // SkipVerify. + PlainHTTPRegistries []string } // NewRemote returns a Remote that reaches the registry as cfg says. The CA @@ -83,7 +96,11 @@ type TLS struct { func NewRemote(cfg TLS) (Remote, error) { // Without a certificate setting, the library default transport does. if cfg.CAFile == "" && !cfg.SkipVerify { - return Remote{plainHTTP: cfg.PlainHTTP}, nil + plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) + if err != nil { + return Remote{}, err + } + return Remote{plainHTTP: plain}, nil } // The library declares its default as an *http.Transport. return newRemote(cfg, remote.DefaultTransport.(*http.Transport)) @@ -96,9 +113,13 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { case cfg.CAFile != "" && cfg.SkipVerify: return Remote{}, errors.Wrap(ErrTLS, errors.WithDetail("a CA file is pointless when certificates are not verified")) - case cfg.PlainHTTP && (cfg.CAFile != "" || cfg.SkipVerify): + case len(cfg.PlainHTTPRegistries) > 0 && cfg.SkipVerify: return Remote{}, errors.Wrap(ErrTLS, - errors.WithDetail("plain HTTP is for a registry without TLS, it takes no certificate setting")) + errors.WithDetail("plain HTTP registries are not meant for a test cluster that verifies no certificate")) + } + plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) + if err != nil { + return Remote{}, err } t := base.Clone() switch { @@ -111,7 +132,31 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { } t.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} } - return Remote{transport: t}, nil + return Remote{transport: t, plainHTTP: plain}, nil +} + +// plainHTTPRegistries checks each entry is a host[:port] and normalizes it the +// way a parsed reference names its registry, so that docker.io matches what +// the library calls index.docker.io. +func plainHTTPRegistries(entries []string) ([]string, error) { + var out []string + for _, e := range entries { + // An empty name would read as the default registry, Docker Hub. + if e == "" { + return nil, errors.Wrap(ErrPlainHTTPRegistry, + errors.WithDetail("an entry is empty, want host[:port]")) + } + reg, err := name.NewRegistry(e, name.StrictValidation) + if err != nil { + return nil, errors.Wrap(ErrPlainHTTPRegistry, errors.CausedBy(err), + errors.WithDetail("want host[:port], with no scheme and no path"), + errors.WithProperty("registry", e)) + } + if s := reg.RegistryStr(); !slices.Contains(out, s) { + out = append(out, s) + } + } + return out, nil } // caPool returns the system CAs plus those of the PEM file at path. The given @@ -156,20 +201,26 @@ func (r Remote) Resolve(ctx context.Context, ref string) (Image, error) { // open resolves ref to its linux/amd64 image. It reads the manifest and the // configuration, never a layer: those are fetched as the stream is read. func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { - var nameOpts []name.Option - if r.plainHTTP { - // The library then races HTTPS and HTTP, see "Pulling and - // extraction" in agent/DESIGN.md. - nameOpts = append(nameOpts, name.Insecure) + parsed, err := name.ParseReference(ref) + if err == nil && slices.Contains(r.plainHTTP, parsed.Context().RegistryStr()) { + // The library then races HTTPS and HTTP for this registry alone, + // see "Pulling and extraction" in agent/DESIGN.md. + parsed, err = name.ParseReference(ref, name.Insecure) } - parsed, err := name.ParseReference(ref, nameOpts...) if err != nil { return nil, Image{}, errors.Wrap(ErrReference, errors.CausedBy(err), errors.WithProperty("source", ref)) } - opts := []remote.Option{remote.WithContext(ctx), remote.WithPlatform(platform)} - if r.transport != nil { - opts = append(opts, remote.WithTransport(r.transport)) + // Read at each pull rather than once, so the library default stays the + // one in force, as it would be without a transport of ours. + next := r.transport + if next == nil { + next = remote.DefaultTransport + } + opts := []remote.Option{ + remote.WithContext(ctx), + remote.WithPlatform(platform), + remote.WithTransport(httpsOnly{next: next, plain: r.plainHTTP}), } img, err := remote.Image(parsed, opts...) if err != nil { @@ -180,6 +231,27 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { return img, id, err } +// httpsOnly refuses a plain HTTP request to any registry that is not listed. +// Marking a registry insecure is not the only way the library reaches for +// HTTP: it also races HTTP for a private or loopback IP address and for a +// localhost name, whatever the list says, see "Pulling and extraction" in +// agent/DESIGN.md. That cannot be turned off, so the request is stopped here, +// on its way out, and only the HTTPS attempt is left to answer. +type httpsOnly struct { + next http.RoundTripper + // plain is Remote.plainHTTP: the library builds its URLs on the same + // RegistryStr, so a listed registry's requests carry it as their host. + plain []string +} + +// RoundTrip implements http.RoundTripper. +func (t httpsOnly) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Scheme != "https" && !slices.Contains(t.plain, req.URL.Host) { + return nil, errors.Wrap(ErrUnlistedPlainHTTP, errors.WithProperty("registry", req.URL.Host)) + } + return t.next.RoundTrip(req) +} + // Tarball reads an image out of a docker archive on the local filesystem, // which is the form the ISO ships for a node that has no registry to reach. type Tarball struct{} diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index a9f49cf..71ee2ae 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -66,7 +66,7 @@ func TestRemotePullStreamsTheImageFiles(t *testing.T) { t.Fatal(err) } - rc, digest, err := Remote{}.Pull(context.Background(), ref) + rc, digest, err := listing(t, ref).Pull(context.Background(), ref) if err != nil { t.Fatal(err) } @@ -136,7 +136,7 @@ func TestRemotePullResolvesMultiArchIndex(t *testing.T) { t.Fatal(err) } - rc, digest, err := Remote{}.Pull(context.Background(), ref) + rc, digest, err := listing(t, ref).Pull(context.Background(), ref) if err != nil { t.Fatal(err) } @@ -226,7 +226,7 @@ func TestRemotePullNoMatchingPlatform(t *testing.T) { t.Fatal(err) } - if _, _, err := (Remote{}).Pull(context.Background(), ref); err == nil { + if _, _, err := listing(t, ref).Pull(context.Background(), ref); err == nil { t.Fatal("want error when the index has no linux/amd64 child") } } @@ -246,7 +246,7 @@ func TestRemotePullRefusesASingleManifestOfAnotherPlatform(t *testing.T) { t.Fatal(err) } - _, _, err = (Remote{}).Pull(context.Background(), ref) + _, _, err = listing(t, ref).Pull(context.Background(), ref) if !errors.Is(err, ErrPull) { t.Fatalf("Pull: err = %v, want ErrPull", err) } @@ -254,7 +254,7 @@ func TestRemotePullRefusesASingleManifestOfAnotherPlatform(t *testing.T) { t.Errorf("err = %v, want both architectures named", err) } // Adoption resolves the source without pulling it. - if _, err := (Remote{}).Resolve(context.Background(), ref); !errors.Is(err, ErrPull) { + if _, err := listing(t, ref).Resolve(context.Background(), ref); !errors.Is(err, ErrPull) { t.Errorf("Resolve: err = %v, want ErrPull", err) } } @@ -274,7 +274,7 @@ func TestRemotePullContextCancelled(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, _, err := (Remote{}).Pull(ctx, ref); err == nil { + if _, _, err := listing(t, ref).Pull(ctx, ref); err == nil { t.Fatal("want error on an already-cancelled context") } } @@ -630,7 +630,7 @@ func TestRemotePullRefusesALayerAlteredInTransit(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { ref := servedTampered(t, img, layerDigest.String(), tc.tamper) - rc, _, err := (Remote{}).Pull(t.Context(), ref) + rc, _, err := listing(t, ref).Pull(t.Context(), ref) if err != nil { t.Fatal(err) } @@ -1026,7 +1026,7 @@ func TestBothPullersAgreeOnTheLayers(t *testing.T) { } for via, resolve := range map[string]func() (Image, error){ - "registry": func() (Image, error) { return Remote{}.Resolve(t.Context(), ref) }, + "registry": func() (Image, error) { return listing(t, ref).Resolve(t.Context(), ref) }, "archive": func() (Image, error) { return Tarball{}.Resolve(t.Context(), path) }, } { id, err := resolve() @@ -1067,7 +1067,7 @@ func TestRemoteResolveReadsNoLayer(t *testing.T) { return b }) - id, err := Remote{}.Resolve(t.Context(), ref) + id, err := listing(t, ref).Resolve(t.Context(), ref) if err != nil { t.Fatal(err) } @@ -1279,6 +1279,51 @@ func plainRegistry(t *testing.T) (ref string, base *http.Transport) { return "example.com:" + port + workerRefPath, base } +// plainHost is a registry entry for the tests that only build a Remote. +const plainHost = "registry.local:5000" + +// registryOf returns the registry a reference names, as the list matches it. +func registryOf(t *testing.T, ref string) string { + t.Helper() + parsed, err := name.ParseReference(ref) + if err != nil { + t.Fatal(err) + } + return parsed.Context().RegistryStr() +} + +// listing returns a Remote that may reach the registry ref names over plain +// HTTP. httptest.NewServer serves plain HTTP on a loopback address, which is +// HTTPS only like any other registry that is not listed. +func listing(t *testing.T, ref string) Remote { + t.Helper() + return Remote{plainHTTP: []string{registryOf(t, ref)}} +} + +// loopbackTransport reaches any test server by the port its address carries: +// both registries are named example.com, and only their ports tell them apart. +func loopbackTransport(caFile string, t *testing.T) *http.Transport { + t.Helper() + base := remote.DefaultTransport.(*http.Transport).Clone() + base.Proxy = nil + dialer := &net.Dialer{} + base.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + _, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + return dialer.DialContext(ctx, network, net.JoinHostPort("127.0.0.1", port)) + } + if caFile != "" { + pool, err := caPool(caFile) + if err != nil { + t.Fatal(err) + } + base.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + } + return base +} + func TestRemotePullNeedsPlainHTTPForARegistryWithoutTLS(t *testing.T) { ref, base := plainRegistry(t) @@ -1291,7 +1336,7 @@ func TestRemotePullNeedsPlainHTTPForARegistryWithoutTLS(t *testing.T) { t.Errorf("err = %v, want an HTTPS request refused", err) } - rc, _, err := Remote{transport: base, plainHTTP: true}.Pull(context.Background(), ref) + rc, _, err := Remote{transport: base, plainHTTP: []string{registryOf(t, ref)}}.Pull(context.Background(), ref) if err != nil { t.Fatal(err) } @@ -1304,17 +1349,79 @@ func TestRemotePullNeedsPlainHTTPForARegistryWithoutTLS(t *testing.T) { } } -// A registry that serves HTTPS stays reachable with plain HTTP allowed. The -// test server only speaks TLS, so a pull that succeeds went over HTTPS. -func TestRemotePullWithPlainHTTPStillReachesAnHTTPSRegistry(t *testing.T) { - ref, caFile, base := tlsRegistry(t) - pool, err := caPool(caFile) +// Only a listed registry is reached over plain HTTP. Another one, the same +// host on another port or listed without its port, is still asked over HTTPS. +func TestRemotePullReachesAnUnlistedRegistryOverHTTPSOnly(t *testing.T) { + ref, base := plainRegistry(t) + for label, listed := range map[string][]string{ + "another port": {"example.com:1"}, + "no port": {"example.com"}, + "by IP": {"127.0.0.1:" + strings.Split(registryOf(t, ref), ":")[1]}, + } { + t.Run(label, func(t *testing.T) { + _, _, err := Remote{transport: base, plainHTTP: listed}.Pull(context.Background(), ref) + if !errors.Is(err, ErrPull) || !strings.Contains(err.Error(), "HTTP response to HTTPS client") { + t.Fatalf("err = %v, want an HTTPS request refused", err) + } + }) + } +} + +// On its own, the library also races plain HTTP for a private or loopback IP +// address and for a localhost name, listed or not. The registry here only +// speaks plain HTTP and counts the requests that reach it: unlisted, none may, +// and the pull fails; listed, the same pull succeeds, which shows every name +// was routed to it all along. +func TestRemotePullNeverReachesAnUnlistedLocalRegistryOverHTTP(t *testing.T) { + var reached atomic.Int32 + reg := registry.New() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached.Add(1) + reg.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + img, err := crane.Image(map[string][]byte{etcdTarPath: []byte(etcdBody)}) if err != nil { t.Fatal(err) } - base.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + host := strings.TrimPrefix(srv.URL, "http://") + if err := crane.Push(img, host+workerRefPath); err != nil { + t.Fatal(err) + } + _, port, _ := net.SplitHostPort(host) + base := loopbackTransport("", t) + + for _, h := range []string{"10.0.0.1", "172.16.0.1", "192.168.0.1", "127.0.0.1", "registry.localhost"} { + t.Run(h, func(t *testing.T) { + ref := net.JoinHostPort(h, port) + workerRefPath + + reached.Store(0) + _, _, err := Remote{transport: base}.Pull(t.Context(), ref) + if !errors.Is(err, ErrPull) || !strings.Contains(err.Error(), ErrUnlistedPlainHTTP.Error()) { + t.Fatalf("err = %v, want the plain HTTP attempt refused", err) + } + if n := reached.Load(); n != 0 { + t.Errorf("%d plain HTTP requests reached an unlisted registry", n) + } + + rc, _, err := Remote{transport: base, plainHTTP: []string{registryOf(t, ref)}}.Pull(t.Context(), ref) + if err != nil { + t.Fatalf("listed: %v", err) + } + if _, err := readAll(t, rc); err != nil { + t.Fatal(err) + } + }) + } +} + +// A listed registry that serves HTTPS stays reachable. The test server only +// speaks TLS, so a pull that succeeds went over HTTPS. +func TestRemotePullWithPlainHTTPStillReachesAnHTTPSRegistry(t *testing.T) { + ref, caFile, _ := tlsRegistry(t) - rc, _, err := Remote{transport: base, plainHTTP: true}.Pull(context.Background(), ref) + r := Remote{transport: loopbackTransport(caFile, t), plainHTTP: []string{registryOf(t, ref)}} + rc, _, err := r.Pull(context.Background(), ref) if err != nil { t.Fatal(err) } @@ -1323,25 +1430,87 @@ func TestRemotePullWithPlainHTTPStillReachesAnHTTPSRegistry(t *testing.T) { } } +// The case the global flag could not serve: a plain HTTP registry and one +// signed by a private CA, in the same run. Listing the first one leaves the +// second one checked, so it still fails on a certificate it cannot verify. +func TestRemotePullsFromAListedPlainRegistryAndAnHTTPSOne(t *testing.T) { + plainRef, _ := plainRegistry(t) + tlsRef, caFile, _ := tlsRegistry(t) + cfg := TLS{CAFile: caFile, PlainHTTPRegistries: []string{registryOf(t, plainRef)}} + + r, err := newRemote(cfg, loopbackTransport("", t)) + if err != nil { + t.Fatal(err) + } + for _, ref := range []string{plainRef, tlsRef} { + rc, _, err := r.Pull(context.Background(), ref) + if err != nil { + t.Fatalf("pulling %s: %v", ref, err) + } + if _, err := readAll(t, rc); err != nil { + t.Fatal(err) + } + } + + // Without the CA, the system pool does not know the test certificate. + // httptest signs every server with the same one, so a second CA file + // would not tell anything apart. + r = Remote{transport: loopbackTransport("", t), plainHTTP: r.plainHTTP} + _, _, err = r.Pull(context.Background(), tlsRef) + if _, ok := errors.AsType[x509.UnknownAuthorityError](err); !ok { + t.Errorf("err = %v, want an unknown authority", err) + } +} + func TestNewRemoteWithPlainHTTPKeepsTheDefaultTransport(t *testing.T) { - r, err := NewRemote(TLS{PlainHTTP: true}) + r, err := NewRemote(TLS{PlainHTTPRegistries: []string{plainHost}}) if err != nil { t.Fatal(err) } - if r.transport != nil || !r.plainHTTP { - t.Errorf("remote = %+v, want the library default transport and plain HTTP", r) + if r.transport != nil || !slices.Equal(r.plainHTTP, []string{plainHost}) { + t.Errorf("remote = %+v, want the library default transport and the registry listed", r) } } -func TestNewRemoteRefusesPlainHTTPWithACertificateSetting(t *testing.T) { - for label, cfg := range map[string]TLS{ - "CA file": {PlainHTTP: true, CAFile: "ca.crt"}, - "skip verify": {PlainHTTP: true, SkipVerify: true}, - } { - t.Run(label, func(t *testing.T) { - if _, err := NewRemote(cfg); !errors.Is(err, ErrTLS) { - t.Fatalf("err = %v, want ErrTLS", err) +// docker.io is index.docker.io once a reference is parsed: the entry must +// match what the reference names, so it is normalized the same way. +func TestNewRemoteNormalizesThePlainHTTPRegistries(t *testing.T) { + r, err := NewRemote(TLS{PlainHTTPRegistries: []string{"docker.io", "10.0.0.1:5000", "docker.io"}}) + if err != nil { + t.Fatal(err) + } + want := []string{registryOf(t, "nginx"), "10.0.0.1:5000"} + if !slices.Equal(r.plainHTTP, want) { + t.Errorf("plain HTTP registries = %v, want %v", r.plainHTTP, want) + } +} + +func TestNewRemoteRefusesAPlainHTTPRegistryThatIsNotAHost(t *testing.T) { + for _, entry := range []string{"", "http://registry.local", "registry.local/repo"} { + t.Run(entry, func(t *testing.T) { + _, err := NewRemote(TLS{PlainHTTPRegistries: []string{entry}}) + if !errors.Is(err, ErrPlainHTTPRegistry) { + t.Fatalf("err = %v, want ErrPlainHTTPRegistry", err) } }) } } + +func TestNewRemoteTakesPlainHTTPRegistriesWithACAFile(t *testing.T) { + _, caFile, _ := tlsRegistry(t) + + r, err := NewRemote(TLS{CAFile: caFile, PlainHTTPRegistries: []string{plainHost}}) + if err != nil { + t.Fatal(err) + } + if r.transport == nil || len(r.plainHTTP) != 1 { + t.Errorf("remote = %+v, want the CA transport and the registry listed", r) + } +} + +func TestNewRemoteRefusesPlainHTTPRegistriesWithSkipVerify(t *testing.T) { + _, err := NewRemote(TLS{SkipVerify: true, PlainHTTPRegistries: []string{plainHost}}) + if !errors.Is(err, ErrTLS) { + t.Fatalf("err = %v, want ErrTLS", err) + } +} diff --git a/agent/test/e2e/e2e_test.go b/agent/test/e2e/e2e_test.go index 2c6dd57..e15fe3b 100644 --- a/agent/test/e2e/e2e_test.go +++ b/agent/test/e2e/e2e_test.go @@ -94,8 +94,9 @@ const ( const cachePath = "/var/lib/image-cache" // registryNamespace holds the two registries the agent pulls from, one plain -// HTTP and one TLS. Sources name them by their Service, a host name: without -// --plain-http the agent only tries HTTPS, as it would for a real registry. +// HTTP and one TLS. Sources name them by their Service, a host name: unless +// --plain-http-registry lists it, the agent only tries HTTPS, as it would for +// a real registry. const registryNamespace = "image-cache-e2e-registry" // registryVersion pins the registry by digest, as it is pulled from Docker Hub @@ -323,9 +324,8 @@ spec: deployRegistry("registry", "") digest := pushCarrier("registry", nil) - By("restarting the agent with --plain-http") - patchAgent("--type=json", - `-p=[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http"}]`) + By("restarting the agent with the plain HTTP registry listed") + allowPlainHTTP("registry") By("creating an ImageCache that selects the worker only") worker, controlPlane := utils.WorkerNode(), utils.ControlPlaneNode() @@ -431,9 +431,8 @@ spec: adoptedInode := seedWithImagecachectl(bin, worker, adoptedName, carrierBody) seedWithImagecachectl(bin, worker, replacedName, "another image") - By("restarting the agent with --plain-http") - patchAgent("--type=json", - `-p=[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http"}]`) + By("restarting the agent with the plain HTTP registry listed") + allowPlainHTTP("registry") By("creating the two ImageCaches the seeded directories stand for") applyImageCache(adoptedName, worker, "registry") @@ -479,8 +478,8 @@ spec: }) // patchAgent patches the agent DaemonSet, waits for the new pods, and rolls -// the change back when the spec ends: --plain-http and --ca-file exclude each -// other, so each spec starts from the shipped manifests. +// the change back when the spec ends, so each spec starts from the shipped +// manifests. func patchAgent(args ...string) { cmd := exec.Command("kubectl", append([]string{"patch", "daemonset", daemonSetName, "-n", namespace}, args...)...) _, err := utils.Run(cmd) @@ -500,6 +499,14 @@ func patchAgent(args ...string) { waitAgentRollout() } +// allowPlainHTTP restarts the agent with the named in-cluster registry listed +// in --plain-http-registry, written as applyImageCache's sources name it. +func allowPlainHTTP(registry string) { + arg := fmt.Sprintf("--plain-http-registry=%s.%s.svc.cluster.local:5000", registry, registryNamespace) + patchAgent("--type=json", + `-p=[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"`+arg+`"}]`) +} + func waitAgentRollout() { cmd := exec.Command("kubectl", "rollout", "status", "daemonset/"+daemonSetName, "-n", namespace, "--timeout=2m") _, err := utils.Run(cmd) From 0c69d804f31678696519bff62bbec16777eb0e79 Mon Sep 17 00:00:00 2001 From: riad Date: Tue, 24 Nov 2026 12:18:05 +0100 Subject: [PATCH 2/6] fix(agent): refuse plain HTTP to the pulled registry only (MK8S-451) A registry on HTTPS that redirects its blobs to storage on plain HTTP failed the pull. Only the pulled registry is held to HTTPS now: a redirect elsewhere is safe, each blob is checked against its digest. --- agent/DESIGN.md | 5 +++- agent/internal/puller/puller.go | 15 ++++++----- agent/internal/puller/puller_test.go | 40 ++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/agent/DESIGN.md b/agent/DESIGN.md index 6315fe8..9091523 100644 --- a/agent/DESIGN.md +++ b/agent/DESIGN.md @@ -314,7 +314,10 @@ Pulling and extraction use address, or a `localhost` host name, and nothing turns that off. The agent hands it a transport that refuses any plain HTTP request to a registry that is not listed, before the request leaves, so only the HTTPS attempt is left - to answer and a bad certificate fails the pull again. Without it, a registry + to answer and a bad certificate fails the pull again. It only checks the + registry of the pulled image: a redirect to another host, such as blob + storage on plain HTTP, goes through, each blob being checked against its + digest. Without it, a registry on a private address, the usual case on premises, would be reached over plain HTTP whatever the list says. `imagecachectl import` goes through the same transport: without `--plain-http` it refuses plain HTTP to such an diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index 41d20e6..2bb2dc8 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -220,7 +220,7 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { opts := []remote.Option{ remote.WithContext(ctx), remote.WithPlatform(platform), - remote.WithTransport(httpsOnly{next: next, plain: r.plainHTTP}), + remote.WithTransport(httpsOnly{next: next, plain: r.plainHTTP, registry: parsed.Context().RegistryStr()}), } img, err := remote.Image(parsed, opts...) if err != nil { @@ -231,22 +231,23 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { return img, id, err } -// httpsOnly refuses a plain HTTP request to any registry that is not listed. -// Marking a registry insecure is not the only way the library reaches for -// HTTP: it also races HTTP for a private or loopback IP address and for a +// httpsOnly refuses a plain HTTP request to the pulled registry unless it is +// listed. The library also races HTTP for a private or loopback IP and for a // localhost name, whatever the list says, see "Pulling and extraction" in -// agent/DESIGN.md. That cannot be turned off, so the request is stopped here, -// on its way out, and only the HTTPS attempt is left to answer. +// agent/DESIGN.md, so the request is stopped here. A redirect to another host, +// such as blob storage, is left alone: each blob is checked against its digest. type httpsOnly struct { next http.RoundTripper // plain is Remote.plainHTTP: the library builds its URLs on the same // RegistryStr, so a listed registry's requests carry it as their host. plain []string + // registry is the RegistryStr of the image being pulled. + registry string } // RoundTrip implements http.RoundTripper. func (t httpsOnly) RoundTrip(req *http.Request) (*http.Response, error) { - if req.URL.Scheme != "https" && !slices.Contains(t.plain, req.URL.Host) { + if req.URL.Scheme != "https" && req.URL.Host == t.registry && !slices.Contains(t.plain, req.URL.Host) { return nil, errors.Wrap(ErrUnlistedPlainHTTP, errors.WithProperty("registry", req.URL.Host)) } return t.next.RoundTrip(req) diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index 71ee2ae..572572b 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -1415,6 +1415,46 @@ func TestRemotePullNeverReachesAnUnlistedLocalRegistryOverHTTP(t *testing.T) { } } +// A registry on HTTPS may redirect its blobs to storage on plain HTTP. Only +// the pulled registry is held to HTTPS, so the pull goes through. +func TestRemotePullFollowsABlobRedirectToPlainHTTPStorage(t *testing.T) { + reg := registry.New() + storage := httptest.NewServer(reg) + t.Cleanup(storage.Close) + _, storagePort, _ := net.SplitHostPort(strings.TrimPrefix(storage.URL, "http://")) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/") { + http.Redirect(w, r, "http://storage.example:"+storagePort+r.URL.Path, http.StatusTemporaryRedirect) + return + } + reg.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + + img, err := crane.Image(map[string][]byte{etcdTarPath: []byte(etcdBody)}) + if err != nil { + t.Fatal(err) + } + host := strings.TrimPrefix(srv.URL, "https://") + if err := crane.Push(img, host+workerRefPath, crane.WithTransport(srv.Client().Transport)); err != nil { + t.Fatal(err) + } + caFile := filepath.Join(t.TempDir(), "ca.crt") + block := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(caFile, block, 0o600); err != nil { + t.Fatal(err) + } + _, port, _ := net.SplitHostPort(host) + + rc, _, err := Remote{transport: loopbackTransport(caFile, t)}.Pull(t.Context(), "example.com:"+port+workerRefPath) + if err != nil { + t.Fatal(err) + } + if _, err := readAll(t, rc); err != nil { + t.Fatal(err) + } +} + // A listed registry that serves HTTPS stays reachable. The test server only // speaks TLS, so a pull that succeeds went over HTTPS. func TestRemotePullWithPlainHTTPStillReachesAnHTTPSRegistry(t *testing.T) { From 5f87d502f7ca70b37f5da34e1dcea5bed3185df6 Mon Sep 17 00:00:00 2001 From: riad Date: Tue, 24 Nov 2026 12:18:13 +0100 Subject: [PATCH 3/6] test(agent): pull from an unlisted HTTPS registry by IP (MK8S-451) --- agent/internal/puller/puller_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index 572572b..87826f7 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -1415,6 +1415,23 @@ func TestRemotePullNeverReachesAnUnlistedLocalRegistryOverHTTP(t *testing.T) { } } +// An unlisted registry on a loopback IP that serves HTTPS: the library also +// tries plain HTTP for it, the transport refuses that attempt, and the HTTPS +// one must still win. +func TestRemotePullReachesAnUnlistedHTTPSRegistryByIP(t *testing.T) { + ref, caFile, _ := tlsRegistry(t) + _, port, _ := net.SplitHostPort(registryOf(t, ref)) + ref = net.JoinHostPort("127.0.0.1", port) + workerRefPath + + rc, _, err := Remote{transport: loopbackTransport(caFile, t)}.Pull(t.Context(), ref) + if err != nil { + t.Fatal(err) + } + if _, err := readAll(t, rc); err != nil { + t.Fatal(err) + } +} + // A registry on HTTPS may redirect its blobs to storage on plain HTTP. Only // the pulled registry is held to HTTPS, so the pull goes through. func TestRemotePullFollowsABlobRedirectToPlainHTTPStorage(t *testing.T) { From 3333b6b4d4144faee32ad3714776e93043bd367b Mon Sep 17 00:00:00 2001 From: riad Date: Tue, 24 Nov 2026 12:20:14 +0100 Subject: [PATCH 4/6] test(agent): e2e refusal of an unlisted registry named by IP (MK8S-451) The registries are named by their Service, so the library never tried plain HTTP for them. A source with the ClusterIP, a private address, stays pending unlisted and syncs once listed. --- agent/test/e2e/e2e_test.go | 61 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/agent/test/e2e/e2e_test.go b/agent/test/e2e/e2e_test.go index e15fe3b..d25fafd 100644 --- a/agent/test/e2e/e2e_test.go +++ b/agent/test/e2e/e2e_test.go @@ -78,6 +78,10 @@ const agentSelector = "control-plane=controller-manager" // synced label, then garbage collection once it is deleted. const syncedName = "imagecache-e2e-synced" +// plainIPName is the ImageCache that names the plain HTTP registry by its +// ClusterIP, a private address the library also tries over plain HTTP. +const plainIPName = "imagecache-e2e-plain-ip" + // tlsName is the ImageCache that pulls from the registry signed by a // throwaway CA, to exercise --ca-file through the shipped patch. const tlsName = "imagecache-e2e-tls" @@ -371,6 +375,46 @@ spec: }).Should(Succeed()) }) + It("should refuse an unlisted plain HTTP registry named by its ClusterIP, then pull once it is listed", func() { + deployRegistry("registry", "") + digest := pushCarrier("registry", nil) + cmd := exec.Command("kubectl", "get", "svc", "registry", "-n", registryNamespace, + "-o", "jsonpath={.spec.clusterIP}") + ip, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to get the registry ClusterIP") + host := net.JoinHostPort(ip, "5000") + + By("creating an ImageCache that names the registry by its ClusterIP, unlisted") + worker := utils.WorkerNode() + applyImageCacheFrom(plainIPName, worker, host+"/e2e/carrier:1") + + By("waiting for the agent to refuse the plain HTTP attempt") + Eventually(func() (string, error) { + cmd := exec.Command("kubectl", "logs", "-l", agentSelector, "-n", namespace, "--tail=-1") + return utils.Run(cmd) + }).Should(ContainSubstring("plain HTTP to an unlisted registry refused")) + labels, err := nodeLabels(worker) + Expect(err).NotTo(HaveOccurred()) + Expect(labels).To(HaveKeyWithValue(labelKey(plainIPName), "pending")) + + By("restarting the agent with the ClusterIP listed") + listPlainHTTP(host) + Eventually(func(g Gomega) { + labels, err := nodeLabels(worker) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(labels).To(HaveKeyWithValue(labelKey(plainIPName), "synced")) + }).Should(Succeed()) + expectExtracted(worker, cachePath+"/"+plainIPName, digest) + + By("deleting the ImageCache, so no agent-owned state outlives the run") + cmd = exec.Command("kubectl", "delete", "imagecache", plainIPName) + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to delete the ImageCache") + Eventually(func() (bool, error) { + return pathExists(worker, cachePath+"/"+plainIPName) + }).Should(BeFalse()) + }) + It("should refuse a registry signed by an unknown CA, then pull once the registry CA patch is applied", func() { ca, cert, key := newRegistryCerts("registry-tls." + registryNamespace + ".svc.cluster.local") deployRegistry("registry-tls", tlsSecret("registry-tls", cert, key)) @@ -502,7 +546,12 @@ func patchAgent(args ...string) { // allowPlainHTTP restarts the agent with the named in-cluster registry listed // in --plain-http-registry, written as applyImageCache's sources name it. func allowPlainHTTP(registry string) { - arg := fmt.Sprintf("--plain-http-registry=%s.%s.svc.cluster.local:5000", registry, registryNamespace) + listPlainHTTP(fmt.Sprintf("%s.%s.svc.cluster.local:5000", registry, registryNamespace)) +} + +// listPlainHTTP restarts the agent with host listed in --plain-http-registry. +func listPlainHTTP(host string) { + arg := "--plain-http-registry=" + host patchAgent("--type=json", `-p=[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"`+arg+`"}]`) } @@ -516,6 +565,12 @@ func waitAgentRollout() { // applyImageCache creates an ImageCache that selects one node and pulls the // carrier image from the named in-cluster registry. func applyImageCache(name, node, registry string) { + applyImageCacheFrom(name, node, fmt.Sprintf("%s.%s.svc.cluster.local:5000/e2e/carrier:1", registry, registryNamespace)) +} + +// applyImageCacheFrom creates an ImageCache that selects one node and pulls +// source. +func applyImageCacheFrom(name, node, source string) { cmd := exec.Command("kubectl", "apply", "-f", "-") cmd.Stdin = strings.NewReader(fmt.Sprintf(`apiVersion: image-cache.scality.com/v1alpha1 kind: ImageCache @@ -524,8 +579,8 @@ metadata: spec: nodeSelector: kubernetes.io/hostname: %s - source: %s.%s.svc.cluster.local:5000/e2e/carrier:1 -`, name, node, registry, registryNamespace)) + source: %s +`, name, node, source)) _, err := utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to create the ImageCache") } From 3bcc352fc68577c3aacec58e9fd761e0ba088f95 Mon Sep 17 00:00:00 2001 From: riad Date: Tue, 24 Nov 2026 12:20:47 +0100 Subject: [PATCH 5/6] docs(agent): keep the plain HTTP matching rules in the agent README (MK8S-451) They were written in four places. DESIGN.md links to them, the flag help and the TLS godoc keep one line. --- agent/DESIGN.md | 23 ++++++++++------------- agent/cmd/manager/main.go | 5 ++--- agent/internal/puller/puller.go | 7 +------ 3 files changed, 13 insertions(+), 22 deletions(-) diff --git a/agent/DESIGN.md b/agent/DESIGN.md index 9091523..fd5d0b8 100644 --- a/agent/DESIGN.md +++ b/agent/DESIGN.md @@ -317,11 +317,10 @@ Pulling and extraction use to answer and a bad certificate fails the pull again. It only checks the registry of the pulled image: a redirect to another host, such as blob storage on plain HTTP, goes through, each blob being checked against its - digest. Without it, a registry - on a private address, the usual case on premises, would be reached over - plain HTTP whatever the list says. `imagecachectl import` goes through the - same transport: without `--plain-http` it refuses plain HTTP to such an - address too. + digest. Without it, a registry on a private address, the usual case on + premises, would be reached over plain HTTP whatever the list says. + `imagecachectl import` goes through the same transport: without + `--plain-http` it refuses plain HTTP to such an address too. `--plain-http-registry` lists registries, as `host[:port]`, to mark insecure (`name.Insecure`). For those, the client tries HTTPS first, and also HTTP when HTTPS fails or takes more than 300ms: the first answer wins, @@ -333,14 +332,12 @@ Pulling and extraction use registry. Docker's `insecure-registries` and containerd's `hosts.toml` scope it the same way. An entry matches the registry of a parsed reference - (`Context().RegistryStr()`) exactly, after the same normalization, so - `docker.io` matches `index.docker.io`. There is no matching by resolved - address: a registry listed by IP and referenced by name, or listed without - its port, does not match. The list goes with `--ca-file`, which covers the - registries that serve TLS, and excludes `--insecure-skip-tls-verify`, meant - for test clusters only. `imagecachectl import` keeps a `--plain-http` - switch: it pulls one source per run, so the switch already covers that - source's registry alone. + (`Context().RegistryStr()`) exactly, see + [Configuration](README.md#configuration) for how to write one. The list + goes with `--ca-file`, which covers the registries that serve TLS, and + excludes `--insecure-skip-tls-verify`, meant for test clusters only. + `imagecachectl import` keeps a `--plain-http` switch: it pulls one source + per run, so the switch already covers that source's registry alone. The cache images are regular container images (they must remain importable and mountable with `ctr` by provisioning tooling), so an artifact-oriented diff --git a/agent/cmd/manager/main.go b/agent/cmd/manager/main.go index 2c20ade..b32e076 100644 --- a/agent/cmd/manager/main.go +++ b/agent/cmd/manager/main.go @@ -115,9 +115,8 @@ func main() { flag.BoolVar(&skipVerify, "insecure-skip-tls-verify", false, "Accept any registry certificate. For a test cluster set up by hand only.") flag.Var(&plainHTTPRegistries, "plain-http-registry", - "A registry, as host[:port], the agent may reach over plain HTTP. Repeat it for several. "+ - "It must be written as the sources name it: by IP or by name, with the port they carry. "+ - "Any other registry is reached over HTTPS only. Excludes --insecure-skip-tls-verify.") + "A registry, as host[:port] exactly as the sources name it, the agent may reach over plain HTTP. "+ + "Repeatable. Excludes --insecure-skip-tls-verify.") opts := zap.Options{ Development: true, } diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index 2bb2dc8..5ae8d73 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -82,12 +82,7 @@ type TLS struct { // up by hand, never for a node. SkipVerify bool // PlainHTTPRegistries lists the registries, as host[:port], the pull may - // reach over plain HTTP. Only these are: every other registry stays - // HTTPS only, and keeps failing on a bad certificate. The match is exact, - // so a registry listed by IP and referenced by name, or listed without - // the port its references carry, is not one of them. It goes with - // CAFile, which covers the registries that serve TLS, but not with - // SkipVerify. + // reach over plain HTTP, see agent/README.md for the matching rules. PlainHTTPRegistries []string } From 5bb8cd53ce4b839f10669527add034d90dd1564a Mon Sep 17 00:00:00 2001 From: riad Date: Tue, 24 Nov 2026 13:58:53 +0100 Subject: [PATCH 6/6] test(agent): match the refusal as the agent logs it (MK8S-451) --- agent/test/e2e/e2e_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent/test/e2e/e2e_test.go b/agent/test/e2e/e2e_test.go index d25fafd..76e33af 100644 --- a/agent/test/e2e/e2e_test.go +++ b/agent/test/e2e/e2e_test.go @@ -392,7 +392,7 @@ spec: Eventually(func() (string, error) { cmd := exec.Command("kubectl", "logs", "-l", agentSelector, "-n", namespace, "--tail=-1") return utils.Run(cmd) - }).Should(ContainSubstring("plain HTTP to an unlisted registry refused")) + }).Should(ContainSubstring("plain http to an unlisted registry refused: registry='" + host + "'")) labels, err := nodeLabels(worker) Expect(err).NotTo(HaveOccurred()) Expect(labels).To(HaveKeyWithValue(labelKey(plainIPName), "pending"))