diff --git a/README.md b/README.md index 1ba332d..84592ed 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,13 @@ 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, or to the mirror when +`--mirror` is given, 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). +`--mirror=` pulls the source from that registry first, with the +source's registry in `?ns=`, and falls back on the registry the source names. +The host has no cluster DNS: give the mirror as an IP. 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..a8da035 100644 --- a/agent/DESIGN.md +++ b/agent/DESIGN.md @@ -310,15 +310,56 @@ 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 library has no mirror support. `--mirror ` adds one global + mirror, tried before the registry each source names, as containerd does + with `hosts.toml`. The source keeps its real name (`ghcr.io/scality/...`) + and the puller rewrites it to `/:` (or + `@`). Each request to the mirror carries `ns=`, the query + parameter containerd sends, which static-oci-registry prepends to the + repository. Docker Hub goes as `ns=docker.io`. The rewritten reference is + a registry like any other: `--ca-file` covers it, and it is reached over + plain HTTP only if `--plain-http-registry` lists it. Rewriting the reference + rather than the host of each request lets the library pick the scheme and + name the mirror in its errors. + The choice is made when the manifest and the configuration are resolved. + If the mirror fails there, the registry is tried, and when both fail the + error carries both causes. The layers then stream from whichever answered: + a mirror lost during the stream fails the pull, and the next pass resolves + again. The sentinel records the source as the resource gives it, never the + mirror reference. A source that already names the mirror is pulled once, + with no `ns`. One mirror per registry is out of scope. + `imagecachectl import --mirror` does the same. Its `--plain-http` then goes + to the mirror, not to the source's registry: on a node, the mirror is the + local registry, and the source names a real one that keeps HTTPS. It runs + on the host with no cluster DNS, so the mirror is given as a node IP. The cache images are regular container images (they must remain importable and mountable with `ctr` by provisioning tooling), so an artifact-oriented @@ -452,7 +493,8 @@ The agent never writes ImageCache resources (no status, no finalizers). nobody listens on leaves the node `pending`. Two registries run in the cluster: a pull over plain HTTP lands on the selected node only, and a registry signed by a private CA is refused until the shipped CA patch is - applied. An archive rewritten on the node with other content of the same + applied. With `--mirror`, a source the registry does not hold is pulled + from the mirror, then from the registry once the mirror is stopped. An archive rewritten on the node with other content of the same size is extracted again. `imagecachectl` seeds two directories on the worker: the agent adopts the one holding the image its resource names, with no extraction, and replaces the other. diff --git a/agent/README.md b/agent/README.md index 3af65ae..a5650b5 100644 --- a/agent/README.md +++ b/agent/README.md @@ -152,9 +152,31 @@ 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. + +`--mirror=` names a registry every source is pulled from first, as +a containerd mirror is. The `ImageCache` sources keep the real image name, +such as `ghcr.io/scality/x:1.0`, and the agent asks the mirror for +`scality/x:1.0` with `?ns=ghcr.io`. When the mirror fails, the agent pulls +from the registry the source names, and when both fail the error gives both +reasons. The mirror takes `--ca-file` like any registry, and needs to be +listed with `--plain-http-registry` if it serves plain HTTP. See "Image +pulling" in [DESIGN.md](DESIGN.md). 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..559b744 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,9 @@ func main() { var resyncPeriod time.Duration var cachePath string var caFile string - var skipVerify, plainHTTP bool + var skipVerify bool + var plainHTTPRegistries stringList + var mirror string 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 +115,14 @@ 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.") + flag.StringVar(&mirror, "mirror", "", + "A registry, as host[:port], every source is pulled from first. The registry the source "+ + "names is tried next, when the mirror fails. Reached over plain HTTP only if it is "+ + "listed with --plain-http-registry.") opts := zap.Options{ Development: true, } @@ -210,16 +230,25 @@ 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, Mirror: mirror, + }) if err != nil { - setupLog.Error(err, "unable to set up registry TLS") + setupLog.Error(err, "unable to set up the registry access") os.Exit(1) } 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)) + } + + if mirror != "" { + setupLog.Info("sources are pulled from the mirror first", "mirror", mirror) } fw, err := controller.NewFSWatcher(nodeName) diff --git a/agent/internal/cli/cli.go b/agent/internal/cli/cli.go index 2b124ed..3925ccb 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" @@ -51,10 +52,10 @@ const importExample = ` imagecachectl import --name worker-1-0-0 registry.examp // Run executes the command line and returns the process exit code: 0 on // success, ExitInterrupted when the context was cancelled, 1 otherwise. func Run(ctx context.Context, args []string, out, errOut io.Writer) int { - var name, cachePath, caFile string + var name, cachePath, caFile, mirror string var skipVerify, plainHTTP bool importCmd := &cobra.Command{ - Use: "import --name [--cache-path ] [--ca-file | --insecure-skip-tls-verify | --plain-http] ", + Use: "import --name [--cache-path ] [--mirror ] [--ca-file | --insecure-skip-tls-verify | --plain-http] ", Short: "Fill the image cache from a registry or a docker archive", Long: importLong, Example: importExample, @@ -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, Mirror: mirror}, 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) { @@ -97,7 +98,9 @@ func Run(ctx context.Context, args []string, out, errOut io.Writer) int { importCmd.Flags().BoolVar(&skipVerify, "insecure-skip-tls-verify", false, "accept any registry certificate, for a test cluster set up by hand only") importCmd.Flags().BoolVar(&plainHTTP, "plain-http", false, - "allow plain HTTP to the registry, for a registry without TLS") + "allow plain HTTP to the registry, for a registry without TLS: to the mirror when --mirror is given") + importCmd.Flags().StringVar(&mirror, "mirror", "", + "registry, as `host[:port]`, to pull the source from first, before the registry it names") _ = importCmd.MarkFlagRequired("name") root := &cobra.Command{ @@ -145,13 +148,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 +163,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 +220,28 @@ 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 one registry: the puller takes a list, and it is the only entry. +// With a mirror, that registry is the mirror: on a node, the mirror is the +// local registry without TLS, and the registry the source names is a real +// one that keeps HTTPS. +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. + switch ref, err := imgname.ParseReference(source); { + case !plainHTTP: + // Every registry stays HTTPS only. + case tls.Mirror != "": + tls.PlainHTTPRegistries = []string{tls.Mirror} + case 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..1b6c6d9 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 ( @@ -30,9 +31,11 @@ const ( importCmd = "import" nameFlag = "--name" helpFlag = "--help" - etcdTarPath = "images/etcd.tar" - pauseTarPath = "images/pause.tar" - SentinelName = ".image-cache-agent.json" + // cachePathFlag is spelled once for goconst, which counts it in slice literals. + cachePathFlag = "--cache-path" + etcdTarPath = "images/etcd.tar" + pauseTarPath = "images/pause.tar" + SentinelName = ".image-cache-agent.json" ) // archive writes a docker archive shaped like a boot cache image. @@ -49,7 +52,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 +101,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 +287,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 +592,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 +637,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 +713,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 +737,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 +787,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{ @@ -803,3 +834,41 @@ func TestPlainHTTPIsNotAnnouncedForAnArchive(t *testing.T) { t.Errorf("stderr warns about plain HTTP for an archive: %s", errOut) } } + +// pauseContent is what the mirror serves for pause.tar. +const pauseContent = "pause" + +// The source names a registry that does not exist, so only the mirror can +// serve it. --plain-http goes to the mirror. +func TestImportThroughAMirror(t *testing.T) { + ref := served(t, map[string][]byte{pauseTarPath: []byte(pauseContent)}) + mirror, _, _ := strings.Cut(ref, "/") + cacheDir := t.TempDir() + + code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, + "--plain-http", "--mirror", mirror, "registry.invalid:5000/boot-cache/worker:1.0.0") + if code != 0 { + t.Fatalf("exit = %d, want 0 (%s)", code, errOut) + } + got, err := os.ReadFile(filepath.Join(cacheDir, resourceName, "pause.tar")) + if err != nil { + t.Fatal(err) + } + if string(got) != pauseContent { + t.Errorf("pause.tar = %q, want %q", got, pauseContent) + } +} + +func TestMirrorThatIsNotAHostIsNamed(t *testing.T) { + for _, flags := range [][]string{{}, {"--plain-http"}} { + args := append([]string{importCmd, nameFlag, resourceName, cachePathFlag, t.TempDir(), + "--mirror", "https://registry.local"}, flags...) + code, _, errOut := run(t, append(args, "registry.local/boot-cache/worker:1.0.0")...) + if code != 1 { + t.Fatalf("%v: exit = %d, want 1 (%s)", flags, code, errOut) + } + if !strings.Contains(errOut, puller.ErrMirror.Error()) { + t.Errorf("%v: stderr = %s, want the mirror named", flags, errOut) + } + } +} diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index af9d0ff..b3d1b1a 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -5,10 +5,13 @@ import ( "context" "crypto/tls" "crypto/x509" + stderrors "errors" "fmt" "io" "net/http" + "net/url" "os" + "slices" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" @@ -31,6 +34,14 @@ 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") + // ErrMirror covers a mirror that is not a host[:port]. + ErrMirror = errors.New("invalid registry mirror") ) // Image identifies what a source resolved to. @@ -58,12 +69,15 @@ 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 + // mirror is TLS.Mirror, normalized like plainHTTP, or empty. + mirror string } // TLS says how a Remote reaches the registry and checks its certificate. @@ -73,9 +87,19 @@ 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 + // Mirror is a registry, as host[:port], tried before the registry each + // reference names, see "Image pulling" in agent/DESIGN.md. The settings + // above apply to it like to any registry: it is reached over plain HTTP + // only if it is listed in PlainHTTPRegistries. + Mirror string } // NewRemote returns a Remote that reaches the registry as cfg says. The CA @@ -83,7 +107,7 @@ 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 + return withRegistries(Remote{}, cfg) } // The library declares its default as an *http.Transport. return newRemote(cfg, remote.DefaultTransport.(*http.Transport)) @@ -96,9 +120,9 @@ 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")) } t := base.Clone() switch { @@ -111,7 +135,53 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { } t.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} } - return Remote{transport: t}, nil + return withRegistries(Remote{transport: t}, cfg) +} + +// withRegistries checks and normalizes the registries cfg names, and sets +// them on r. +func withRegistries(r Remote, cfg TLS) (Remote, error) { + // The mirror first: imagecachectl copies it into the plain HTTP list, + // and a bad one is better named as the mirror. + if cfg.Mirror != "" { + reg, err := name.NewRegistry(cfg.Mirror, name.StrictValidation) + if err != nil { + return Remote{}, errors.Wrap(ErrMirror, errors.CausedBy(err), + errors.WithDetail("want host[:port], with no scheme and no path"), + errors.WithProperty("mirror", cfg.Mirror)) + } + r.mirror = reg.RegistryStr() + } + plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) + if err != nil { + return Remote{}, err + } + r.plainHTTP = plain + return r, 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 @@ -155,21 +225,75 @@ 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. +// +// With a mirror, the mirror is tried first and the registry ref names next. +// The choice is made here, once: the layers then come from whichever +// answered, and a mirror lost while they stream fails the pull. 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 := r.parse(ref) + if err != nil { + return nil, Image{}, err + } + upstream := parsed.Context().RegistryStr() + if r.mirror == "" || r.mirror == upstream { + return r.openFrom(ctx, parsed, ref, "") + } + sep := ":" + if _, ok := parsed.(name.Digest); ok { + sep = "@" } - parsed, err := name.ParseReference(ref, nameOpts...) + mirrorRef := r.mirror + "/" + parsed.Context().RepositoryStr() + sep + parsed.Identifier() + onMirror, err := r.parse(mirrorRef) if err != nil { - return nil, Image{}, errors.Wrap(ErrReference, errors.CausedBy(err), + return nil, Image{}, err + } + img, id, mirrorErr := r.openFrom(ctx, onMirror, mirrorRef, namespace(upstream)) + // A cancelled pull would fail the same way on the registry. + if mirrorErr == nil || ctx.Err() != nil { + return img, id, mirrorErr + } + img, id, err = r.openFrom(ctx, parsed, ref, "") + if err != nil { + return nil, Image{}, errors.Wrap(ErrPull, errors.CausedBy(stderrors.Join(mirrorErr, err)), + errors.WithDetail("neither the mirror nor the registry served the image"), + errors.WithProperty("source", ref), errors.WithProperty("mirror", r.mirror)) + } + return img, id, nil +} + +// parse parses ref, marked insecure when its registry is listed for plain +// HTTP. +func (r Remote) parse(ref string) (name.Reference, error) { + 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) + } + if err != nil { + return nil, 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)) + return parsed, nil +} + +// openFrom resolves parsed. A non-empty ns is sent to the mirror, see +// withNamespace. +func (r Remote) openFrom(ctx context.Context, parsed name.Reference, ref, ns string) (v1.Image, Image, error) { + // 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 + } + var t http.RoundTripper = httpsOnly{next: next, plain: r.plainHTTP} + if ns != "" { + t = withNamespace{next: t, host: r.mirror, ns: ns} + } + opts := []remote.Option{ + remote.WithContext(ctx), + remote.WithPlatform(platform), + remote.WithTransport(t), } img, err := remote.Image(parsed, opts...) if err != nil { @@ -180,6 +304,62 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { return img, id, err } +// namespace is the ns a mirror receives for a registry. Docker Hub goes by +// docker.io there, as containerd sends it, not by the host the library uses. +func namespace(registry string) string { + if registry == name.DefaultRegistry { + return "docker.io" + } + return registry +} + +// withNamespace adds the ns query parameter to the requests sent to the +// mirror. It names the registry the image comes from, the way containerd +// passes it to a mirror. Requests to any other host, such as a token server +// or a blob storage the mirror redirects to, go out unchanged. +type withNamespace struct { + next http.RoundTripper + host, ns string +} + +// RoundTrip implements http.RoundTripper. +func (t withNamespace) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Host != t.host { + return t.next.RoundTrip(req) + } + // A RoundTripper must not change the request it is given. The query is + // appended to, not encoded again: that would reorder a signed URL. + req = req.Clone(req.Context()) + ns := "ns=" + url.QueryEscape(t.ns) + if req.URL.RawQuery == "" { + req.URL.RawQuery = ns + } else { + req.URL.RawQuery += "&" + ns + } + return t.next.RoundTrip(req) +} + +// 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..0a105d9 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) + } + }) + } +} - rc, _, err := Remote{transport: base, plainHTTP: true}.Pull(context.Background(), ref) +// 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) + + 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,347 @@ 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) + } +} + +// mirrorTest is a plain HTTP registry that records the ns parameter of every +// request it receives. +type mirrorTest struct { + host string + srv *httptest.Server + mu sync.Mutex + ns []string +} + +// newMirrorTest serves an empty in-memory registry. Its host is +// example.com:, reached through loopbackTransport. +func newMirrorTest(t *testing.T) *mirrorTest { + t.Helper() + m := &mirrorTest{} + reg := registry.New() + m.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + m.mu.Lock() + m.ns = append(m.ns, r.URL.Query().Get("ns")) + m.mu.Unlock() + reg.ServeHTTP(w, r) + })) + t.Cleanup(m.srv.Close) + _, port, _ := net.SplitHostPort(strings.TrimPrefix(m.srv.URL, "http://")) + m.host = "example.com:" + port + return m +} + +// push stores img under path, and returns its digest. The push goes to the +// loopback address and is not recorded. +func (m *mirrorTest) push(t *testing.T, path string, img v1.Image) string { + t.Helper() + m.mu.Lock() + before := len(m.ns) + m.mu.Unlock() + if err := crane.Push(img, strings.TrimPrefix(m.srv.URL, "http://")+path); err != nil { + t.Fatal(err) + } + m.mu.Lock() + m.ns = m.ns[:before] + m.mu.Unlock() + d, err := img.Digest() + if err != nil { + t.Fatal(err) + } + return d.String() +} + +func (m *mirrorTest) seen() []string { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.ns) +} + +func workerImage(t *testing.T) v1.Image { + t.Helper() + img, err := crane.Image(map[string][]byte{etcdTarPath: []byte(etcdBody)}) + if err != nil { + t.Fatal(err) + } + return img +} + +// pullAll pulls ref and reads the whole stream, the layers included. +func pullAll(r Remote, ref string) (Image, error) { + rc, id, err := r.Pull(context.Background(), ref) + if err != nil { + return Image{}, err + } + _, err = io.Copy(io.Discard, rc) + if cerr := rc.Close(); err == nil { + err = cerr + } + return id, err +} + +func TestRemotePullTriesTheMirrorFirst(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + // Only the mirror has the image, so a pull that works went through it. + digest := mirror.push(t, workerRefPath, workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host, upstream.host}, + mirror: mirror.host, + } + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + seen := mirror.seen() + if len(seen) == 0 { + t.Fatal("the mirror received no request") + } + for _, ns := range seen { + if ns != upstream.host { + t.Errorf("the mirror received ns=%q, want %q", ns, upstream.host) + } + } + if n := len(upstream.seen()); n != 0 { + t.Errorf("the registry received %d requests, want none", n) + } +} + +func TestRemotePullKeepsTheDigestOnTheMirror(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + digest := mirror.push(t, workerRefPath, workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host, upstream.host}, + mirror: mirror.host, + } + + id, err := pullAll(r, upstream.host+"/boot-cache/worker@"+digest) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } +} + +func TestRemotePullFallsBackOnTheRegistry(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + digest := upstream.push(t, workerRefPath, workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host, upstream.host}, + mirror: mirror.host, + } + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + if len(mirror.seen()) == 0 { + t.Error("the mirror was not tried first") + } + for _, ns := range upstream.seen() { + if ns != "" { + t.Errorf("the registry received ns=%q, want none", ns) + } + } +} + +func TestRemotePullNamesBothFailures(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + mirror.srv.Close() + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host, upstream.host}, + mirror: mirror.host, + } + + _, err := pullAll(r, upstream.host+workerRefPath) + if !errors.Is(err, ErrPull) { + t.Fatalf("err = %v, want ErrPull", err) + } + for _, want := range []string{"connection refused", "NAME_UNKNOWN"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("err = %v, want it to carry %q", err, want) + } + } +} + +// The mirror follows the plain HTTP list like any registry: unlisted, it is +// reached over HTTPS only, which a plain HTTP server cannot answer. +func TestRemotePullReachesAnUnlistedMirrorOverHTTPSOnly(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + mirror.push(t, workerRefPath, workerImage(t)) + digest := upstream.push(t, workerRefPath, workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{upstream.host}, + mirror: mirror.host, + } + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + if n := len(mirror.seen()); n != 0 { + t.Errorf("the mirror received %d plain HTTP requests, want none", n) + } +} + +// Docker Hub references are normalized by the library to index.docker.io and +// library/. The mirror gets the repository as the library names it, and the +// ns containerd would send. +func TestRemotePullSendsDockerHubAsDockerIO(t *testing.T) { + mirror := newMirrorTest(t) + mirror.push(t, "/library/worker:1.0.0", workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host}, + mirror: mirror.host, + } + + if _, err := pullAll(r, "worker:1.0.0"); err != nil { + t.Fatal(err) + } + const dockerHub = "docker.io" + for _, ns := range mirror.seen() { + if ns != dockerHub { + t.Errorf("the mirror received ns=%q, want %s", ns, dockerHub) + } + } +} + +// A source that already names the mirror is pulled once, with no ns. +func TestRemotePullFromTheMirrorItself(t *testing.T) { + mirror := newMirrorTest(t) + mirror.push(t, workerRefPath, workerImage(t)) + r := Remote{ + transport: loopbackTransport("", t), + plainHTTP: []string{mirror.host}, + mirror: mirror.host, + } + + if _, err := pullAll(r, mirror.host+workerRefPath); err != nil { + t.Fatal(err) + } + for _, ns := range mirror.seen() { + if ns != "" { + t.Errorf("the mirror received ns=%q, want none", ns) + } + } +} + +// --ca-file covers the mirror. tlsRegistry dials its server for any host, +// and its certificate covers example.com only: a pull that reached the +// registry instead of the mirror would fail on the name. +func TestRemotePullTrustsTheGivenCAForTheMirror(t *testing.T) { + ref, caFile, base := tlsRegistry(t) + r, err := newRemote(TLS{CAFile: caFile, Mirror: registryOf(t, ref)}, base) + if err != nil { + t.Fatal(err) + } + + if _, err := pullAll(r, "registry.local:5000"+workerRefPath); err != nil { + t.Fatal(err) + } +} + +func TestNewRemoteRejectsAMirrorThatIsNotAHost(t *testing.T) { + for _, m := range []string{"https://registry.local", "registry.local/path", "Registry.local:x"} { + if _, err := NewRemote(TLS{Mirror: m}); !errors.Is(err, ErrMirror) { + t.Errorf("NewRemote(Mirror: %q) err = %v, want ErrMirror", m, err) + } + } +} diff --git a/agent/test/e2e/e2e_test.go b/agent/test/e2e/e2e_test.go index 2c6dd57..60b62b7 100644 --- a/agent/test/e2e/e2e_test.go +++ b/agent/test/e2e/e2e_test.go @@ -78,6 +78,13 @@ const agentSelector = "control-plane=controller-manager" // synced label, then garbage collection once it is deleted. const syncedName = "imagecache-e2e-synced" +// mirroredName and fallbackName are the ImageCaches pulled with --mirror: the +// first from the mirror, the second from the registry once the mirror is down. +const ( + mirroredName = "imagecache-e2e-mirrored" + fallbackName = "imagecache-e2e-fallback" +) + // 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" @@ -94,8 +101,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 +331,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() @@ -371,6 +378,60 @@ spec: }).Should(Succeed()) }) + It("should pull through the mirror first, then from the registry once the mirror is down", func() { + deployRegistry("mirror", "") + deployRegistry("upstream", "") + // The registry has nothing yet: a pull that works went through + // the mirror. + digest := pushCarrier("mirror", nil) + + By("restarting the agent with the mirror") + host := func(registry string) string { + return fmt.Sprintf("%s.%s.svc.cluster.local:5000", registry, registryNamespace) + } + patchAgent("--type=json", fmt.Sprintf(`-p=[`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http-registry=%[1]s"},`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http-registry=%[2]s"},`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--mirror=%[1]s"}]`, + host("mirror"), host("upstream"))) + + worker := utils.WorkerNode() + expectSynced := func(name string) { + By("waiting for " + name + " to be synced on the worker") + Eventually(func(g Gomega) { + labels, err := nodeLabels(worker) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(labels).To(HaveKeyWithValue(labelKey(name), "synced")) + }).Should(Succeed()) + expectExtracted(worker, cachePath+"/"+name, digest) + } + DeferCleanup(func() { + cmd := exec.Command("kubectl", "delete", "imagecache", mirroredName, fallbackName, "--ignore-not-found") + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to delete the ImageCaches") + }) + + By("creating an ImageCache whose source names the registry") + applyImageCache(mirroredName, worker, "upstream") + expectSynced(mirroredName) + + By("pushing the image to the registry and stopping the mirror") + Expect(pushCarrier("upstream", nil)).To(Equal(digest)) + cmd := exec.Command("kubectl", "scale", "deployment/mirror", "-n", registryNamespace, "--replicas=0") + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to stop the mirror") + // Both hold the same digest: a pod still terminating could serve + // the pull and hide a broken fallback. + cmd = exec.Command("kubectl", "wait", "--for=delete", "pod", "-l", "app=mirror", + "-n", registryNamespace, "--timeout=2m") + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "The mirror did not stop") + + By("creating a second ImageCache, pulled from the registry") + applyImageCache(fallbackName, worker, "upstream") + expectSynced(fallbackName) + }) + 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)) @@ -431,9 +492,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 +539,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 +560,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)