Skip to content

Commit 8333d2e

Browse files
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=<host[:port]>, 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.
1 parent 0272a85 commit 8333d2e

9 files changed

Lines changed: 432 additions & 91 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,10 @@ by a private CA, on top of the system ones. It is checked on every run, and
179179
never read for an archive. `--insecure-skip-tls-verify` accepts any
180180
certificate instead, for a test cluster only, and prints a warning.
181181
`--plain-http` reaches a registry that serves plain HTTP, and prints a warning
182-
too. It excludes the two certificate flags.
182+
too. It applies to the registry of the source only, and excludes the two
183+
certificate flags. Without it, the registry is reached over HTTPS only, even
184+
on a private or loopback IP address. The agent takes a list instead, `--plain-http-registry`,
185+
see [agent/README.md](agent/README.md).
183186

184187
The import refuses to replace a directory without a sentinel. The command runs
185188
as root, so a wrong name or cache path that lands on a directory the store did

‎agent/DESIGN.md‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -310,15 +310,34 @@ Pulling and extraction use
310310
unusable one stops the agent at startup rather than failing every pull.
311311
`--insecure-skip-tls-verify` turns verification off for test clusters. It
312312
excludes `--ca-file`, so neither setting wins in silence.
313-
- On its own, the library uses plain HTTP only for a loopback or private IP
314-
address, or a `localhost` host name.
315-
`--plain-http` marks every registry insecure (`name.Insecure`). The client
316-
then tries HTTPS first, and also HTTP when HTTPS fails or takes more than
317-
300ms: the first answer wins, on every pull. So the flag also weakens a
318-
registry that serves HTTPS: a certificate error no longer fails the pull,
319-
and anyone on the path can answer the HTTP attempt (port 80 when the
320-
reference names no port). It is for a registry without TLS, and excludes
321-
both certificate flags rather than mixing the two modes.
313+
- On its own, the library also tries plain HTTP for a loopback or private IP
314+
address, or a `localhost` host name, and nothing turns that off. The agent
315+
hands it a transport that refuses any plain HTTP request to a registry that
316+
is not listed, before the request leaves, so only the HTTPS attempt is left
317+
to answer and a bad certificate fails the pull again. Without it, a registry
318+
on a private address, the usual case on premises, would be reached over
319+
plain HTTP whatever the list says. `imagecachectl import` goes through the
320+
same transport: without `--plain-http` it refuses plain HTTP to such an
321+
address too.
322+
`--plain-http-registry` lists registries, as `host[:port]`, to mark
323+
insecure (`name.Insecure`). For those, the client tries HTTPS first, and
324+
also HTTP when HTTPS fails or takes more than 300ms: the first answer wins,
325+
on every pull. So marking a registry also weakens it if it serves HTTPS: a
326+
certificate error no longer fails the pull, and anyone on the path can
327+
answer the HTTP attempt (port 80 when the reference names no port). That
328+
is why the setting is a list and not a switch: a single global flag would
329+
weaken every HTTPS registry the resources name to serve one plain HTTP
330+
registry. Docker's `insecure-registries` and containerd's `hosts.toml`
331+
scope it the same way.
332+
An entry matches the registry of a parsed reference
333+
(`Context().RegistryStr()`) exactly, after the same normalization, so
334+
`docker.io` matches `index.docker.io`. There is no matching by resolved
335+
address: a registry listed by IP and referenced by name, or listed without
336+
its port, does not match. The list goes with `--ca-file`, which covers the
337+
registries that serve TLS, and excludes `--insecure-skip-tls-verify`, meant
338+
for test clusters only. `imagecachectl import` keeps a `--plain-http`
339+
switch: it pulls one source per run, so the switch already covers that
340+
source's registry alone.
322341

323342
The cache images are regular container images (they must remain importable
324343
and mountable with `ctr` by provisioning tooling), so an artifact-oriented

‎agent/README.md‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,22 @@ On a test cluster set up by hand, `--insecure-skip-tls-verify` accepts any
152152
registry certificate instead. The agent logs a warning at startup. It excludes
153153
`--ca-file`, and no manifest here sets it: never use it on a real node.
154154

155-
A registry that serves plain HTTP needs `--plain-http`. The agent logs a
156-
warning at startup. It excludes `--ca-file` and `--insecure-skip-tls-verify`,
157-
and no manifest here sets it.
155+
A registry that serves plain HTTP needs `--plain-http-registry=<host[:port]>`,
156+
repeated for each one. Only the listed registries may be reached over plain
157+
HTTP: every other one is reached over HTTPS only, and still fails on a bad
158+
certificate. That includes a registry on a private or loopback IP address or
159+
a `localhost` name, which the pull library would otherwise also try over plain
160+
HTTP: list it if it serves plain HTTP. Write each entry as the `ImageCache` sources name the registry:
161+
162+
- by the same host, an IP if they use an IP and a name if they use a name;
163+
- with the port they carry, and with no port if they carry none;
164+
- with no scheme and no path: `10.0.0.1:5000`, not `http://10.0.0.1:5000`.
165+
166+
The match is exact, so an entry written another way does not apply and the
167+
pull fails on `HTTP response to HTTPS client`. The agent logs the list with a
168+
warning at startup. It goes with `--ca-file`, which covers the registries that
169+
serve TLS, but not with `--insecure-skip-tls-verify`. No manifest here sets
170+
it.
158171

159172
Leader election is deliberately absent. Every agent converges the node it runs
160173
on, so there is nothing to elect a leader for.

‎agent/cmd/manager/main.go‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"flag"
2222
"os"
2323
"path/filepath"
24+
"strings"
2425
"time"
2526

2627
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
@@ -59,6 +60,18 @@ func init() {
5960
// +kubebuilder:scaffold:scheme
6061
}
6162

63+
// stringList is a flag that can be repeated, each occurrence adding a value.
64+
type stringList []string
65+
66+
// String implements flag.Value.
67+
func (l *stringList) String() string { return strings.Join(*l, ",") }
68+
69+
// Set implements flag.Value.
70+
func (l *stringList) Set(v string) error {
71+
*l = append(*l, v)
72+
return nil
73+
}
74+
6275
// nolint:gocyclo
6376
func main() {
6477
var metricsAddr string
@@ -70,7 +83,8 @@ func main() {
7083
var resyncPeriod time.Duration
7184
var cachePath string
7285
var caFile string
73-
var skipVerify, plainHTTP bool
86+
var skipVerify bool
87+
var plainHTTPRegistries stringList
7488
var tlsOpts []func(*tls.Config)
7589
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
7690
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
@@ -100,9 +114,10 @@ func main() {
100114
"Read once at startup: restart the agent after rotating it.")
101115
flag.BoolVar(&skipVerify, "insecure-skip-tls-verify", false,
102116
"Accept any registry certificate. For a test cluster set up by hand only.")
103-
flag.BoolVar(&plainHTTP, "plain-http", false,
104-
"Allow plain HTTP to every registry. For a registry without TLS. "+
105-
"Excludes --ca-file and --insecure-skip-tls-verify.")
117+
flag.Var(&plainHTTPRegistries, "plain-http-registry",
118+
"A registry, as host[:port], the agent may reach over plain HTTP. Repeat it for several. "+
119+
"It must be written as the sources name it: by IP or by name, with the port they carry. "+
120+
"Any other registry is reached over HTTPS only. Excludes --insecure-skip-tls-verify.")
106121
opts := zap.Options{
107122
Development: true,
108123
}
@@ -210,16 +225,21 @@ func main() {
210225

211226
// Checked before anything starts: an unusable CA would otherwise surface
212227
// as a failed pull on every node and every resource.
213-
remote, err := puller.NewRemote(puller.TLS{CAFile: caFile, SkipVerify: skipVerify, PlainHTTP: plainHTTP})
228+
remote, err := puller.NewRemote(puller.TLS{
229+
CAFile: caFile, SkipVerify: skipVerify, PlainHTTPRegistries: plainHTTPRegistries,
230+
})
214231
if err != nil {
215232
setupLog.Error(err, "unable to set up registry TLS")
216233
os.Exit(1)
217234
}
218235
if skipVerify {
219236
setupLog.Info("WARNING: registry certificates are not verified (--insecure-skip-tls-verify)")
220237
}
221-
if plainHTTP {
222-
setupLog.Info("WARNING: registries may be reached over plain HTTP (--plain-http)")
238+
if len(plainHTTPRegistries) > 0 {
239+
// Logged in full: an entry that does not match a source exactly
240+
// shows up as "HTTP response to HTTPS client" on the pull.
241+
setupLog.Info("WARNING: these registries may be reached over plain HTTP (--plain-http-registry)",
242+
"registries", []string(plainHTTPRegistries))
223243
}
224244

225245
fw, err := controller.NewFSWatcher(nodeName)

‎agent/internal/cli/cli.go‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"path/filepath"
1313
"strings"
1414

15+
imgname "github.com/google/go-containerregistry/pkg/name"
1516
"github.com/scality/go-errors"
1617
"github.com/spf13/cobra"
1718

@@ -80,7 +81,7 @@ func Run(ctx context.Context, args []string, out, errOut io.Writer) int {
8081
return errors.New("--insecure-skip-tls-verify and --plain-http exclude each other")
8182
}
8283
err := do(cmd.Context(), cachePath, name, args[0],
83-
puller.TLS{CAFile: caFile, SkipVerify: skipVerify, PlainHTTP: plainHTTP}, out, errOut)
84+
puller.TLS{CAFile: caFile, SkipVerify: skipVerify}, plainHTTP, out, errOut)
8485
// An interrupted run is not a failure to diagnose: the extraction
8586
// publishes by rename, so nothing half written is left behind.
8687
if errors.Is(err, context.Canceled) {
@@ -145,21 +146,22 @@ func validate(name, cachePath string) error {
145146
return nil
146147
}
147148

148-
func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, out, errOut io.Writer) error {
149+
func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, plainHTTP bool,
150+
out, errOut io.Writer) error {
149151
store := cache.Store{}
150152

151153
// Before the cache state, so that a CA that cannot be used is reported
152154
// on every run, including one that would have found the resource
153155
// complete, rather than only on the run that finally needs the registry.
154-
src, err := pullerFor(source, tls)
156+
src, err := pullerFor(source, tls, plainHTTP)
155157
if err != nil {
156158
return err
157159
}
158160
if _, remote := src.(puller.Remote); remote {
159161
if tls.SkipVerify {
160162
printf(errOut, "imagecachectl: warning: the registry certificate is not verified\n")
161163
}
162-
if tls.PlainHTTP {
164+
if plainHTTP {
163165
printf(errOut, "imagecachectl: warning: the registry may be reached over plain HTTP\n")
164166
}
165167
}
@@ -216,14 +218,21 @@ func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, out
216218
// file rather than coming back with a complaint about a reference.
217219
//
218220
// The TLS and plain HTTP settings only matter to a registry, so an archive
219-
// never reads them.
220-
func pullerFor(source string, tls puller.TLS) (puller.Puller, error) {
221+
// never reads them. The command pulls one source per run, so plain HTTP is
222+
// allowed to that source's registry: the puller takes a list of registries,
223+
// and this one is the only entry.
224+
func pullerFor(source string, tls puller.TLS, plainHTTP bool) (puller.Puller, error) {
221225
switch {
222226
case strings.HasPrefix(source, string(os.PathSeparator)),
223227
strings.HasPrefix(source, "."),
224228
strings.HasSuffix(source, ".tar"):
225229
return puller.Tarball{}, nil
226230
default:
231+
// A reference that does not parse is reported by the pull, which
232+
// names it as one.
233+
if ref, err := imgname.ParseReference(source); plainHTTP && err == nil {
234+
tls.PlainHTTPRegistries = []string{ref.Context().RegistryStr()}
235+
}
227236
return puller.NewRemote(tls)
228237
}
229238
}

‎agent/internal/cli/cli_test.go‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"github.com/google/go-containerregistry/pkg/v1/remote"
2424
"github.com/google/go-containerregistry/pkg/v1/tarball"
2525
"github.com/scality/image-cache/agent/internal/cache"
26+
"github.com/scality/image-cache/agent/internal/puller"
2627
)
2728

2829
const (
@@ -49,7 +50,9 @@ func archive(t *testing.T, files map[string][]byte) string {
4950
return path
5051
}
5152

52-
// served pushes the same shape to an in-memory registry and returns its reference.
53+
// served pushes the same shape to an in-memory registry and returns its
54+
// reference. The registry serves plain HTTP on a loopback address, which the
55+
// command reaches with --plain-http only, as it would any other registry.
5356
func served(t *testing.T, files map[string][]byte) string {
5457
t.Helper()
5558
srv := httptest.NewServer(registry.New())
@@ -96,7 +99,7 @@ func TestImportFromARegistry(t *testing.T) {
9699
cacheDir := t.TempDir()
97100
ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")})
98101

99-
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, ref)
102+
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http", ref)
100103
if code != 0 {
101104
t.Fatalf("exit = %d, want 0 (%s)", code, errOut)
102105
}
@@ -282,7 +285,7 @@ func TestASourceShapedLikeAReferenceIsNotReadFromDisk(t *testing.T) {
282285
}
283286
t.Chdir(cwd)
284287

285-
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, ref)
288+
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http", ref)
286289
if code != 0 {
287290
t.Fatalf("exit = %d, want 0 (%s)", code, errOut)
288291
}
@@ -587,7 +590,7 @@ func TestImportFailsWhenALayerCannotBeFetched(t *testing.T) {
587590
t.Cleanup(cutting.Close)
588591
cacheDir := t.TempDir()
589592

590-
code, out, _ := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir,
593+
code, out, _ := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, "--plain-http",
591594
strings.TrimPrefix(cutting.URL, "http://")+"/boot-cache/worker:1.0.0")
592595
if code != 1 {
593596
t.Fatalf("exit = %d, want 1 (stdout %q)", code, out)
@@ -632,7 +635,17 @@ func TestCAFileIsNotReadForAnArchive(t *testing.T) {
632635

633636
func TestSkippingTLSVerificationIsAnnounced(t *testing.T) {
634637
cacheDir := t.TempDir()
635-
ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")})
638+
// A certificate nothing trusts: only skipping the verification reaches it.
639+
srv := httptest.NewTLSServer(registry.New())
640+
t.Cleanup(srv.Close)
641+
img, err := crane.Image(map[string][]byte{pauseTarPath: []byte("pause")})
642+
if err != nil {
643+
t.Fatal(err)
644+
}
645+
ref := strings.TrimPrefix(srv.URL, "https://") + "/boot-cache/worker:1.0.0"
646+
if err := crane.Push(img, ref, crane.WithTransport(srv.Client().Transport)); err != nil {
647+
t.Fatal(err)
648+
}
636649

637650
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir,
638651
"--insecure-skip-tls-verify", ref)
@@ -698,7 +711,9 @@ func TestImportRecordsTheSameImageWhateverTheSource(t *testing.T) {
698711
layers := make([][]string, 0, len(sources))
699712
for _, src := range sources {
700713
cacheDir := t.TempDir()
701-
if code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir, src); code != 0 {
714+
// An archive reaches no registry, so --plain-http changes nothing for it.
715+
if code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", cacheDir,
716+
"--plain-http", src); code != 0 {
702717
t.Fatalf("%s: exit = %d (%s)", src, code, errOut)
703718
}
704719
r := readSentinel(t, cacheDir)
@@ -720,8 +735,8 @@ func TestImportRecordsTheSameImageWhateverTheSource(t *testing.T) {
720735

721736
// servedByName is served, but the reference names example.com and the
722737
// library default transport sends every address to the server for the rest
723-
// of the test. go-containerregistry already uses plain HTTP for a loopback
724-
// registry, so only a host name shows what --plain-http changes.
738+
// of the test. A host name is the plain case: the library tries nothing but
739+
// HTTPS for it, so the refusal comes from the registry alone.
725740
func servedByName(t *testing.T, files map[string][]byte) string {
726741
t.Helper()
727742
ref := served(t, files)
@@ -770,6 +785,20 @@ func TestPlainHTTPReachesARegistryWithoutTLS(t *testing.T) {
770785
}
771786
}
772787

788+
// The library would race plain HTTP for a loopback registry on its own. The
789+
// command still refuses it without --plain-http, as it would a host name.
790+
func TestPlainHTTPIsNeededForALoopbackRegistry(t *testing.T) {
791+
ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")})
792+
793+
code, _, errOut := run(t, importCmd, nameFlag, resourceName, "--cache-path", t.TempDir(), ref)
794+
if code != 1 {
795+
t.Fatalf("exit = %d without --plain-http, want 1 (%s)", code, errOut)
796+
}
797+
if !strings.Contains(errOut, puller.ErrUnlistedPlainHTTP.Error()) {
798+
t.Errorf("stderr = %s, want the plain HTTP attempt refused", errOut)
799+
}
800+
}
801+
773802
func TestPlainHTTPExcludesTheCertificateFlags(t *testing.T) {
774803
ref := served(t, map[string][]byte{pauseTarPath: []byte("pause")})
775804
for _, flags := range [][]string{

0 commit comments

Comments
 (0)