Skip to content
Open
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 28 additions & 9 deletions agent/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.
`--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, 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
Expand Down
20 changes: 17 additions & 3 deletions agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<host[:port]>`,
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
Comment thread
ezekiel-alexrod marked this conversation as resolved.
Resolved
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.
Expand Down
33 changes: 26 additions & 7 deletions agent/cmd/manager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"flag"
"os"
"path/filepath"
"strings"
"time"

// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
Expand Down Expand Up @@ -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
Expand All @@ -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.")
Expand Down Expand Up @@ -100,9 +114,9 @@ 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",
Comment thread
riadelhajjaji-scality marked this conversation as resolved.
Resolved
"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,
}
Expand Down Expand Up @@ -210,16 +224,21 @@ 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)
}
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)
Expand Down
21 changes: 15 additions & 6 deletions agent/internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -145,21 +146,22 @@ 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
}
if _, remote := src.(puller.Remote); remote {
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")
}
}
Expand Down Expand Up @@ -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)
}
}
45 changes: 37 additions & 8 deletions agent/internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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())
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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{
Expand Down
Loading
Loading