From 56edbf05b37d76a028563bd22a6bfdf4770b7583 Mon Sep 17 00:00:00 2001 From: vvvomit Date: Fri, 30 Oct 2026 00:28:35 +0330 Subject: [PATCH] serve-registry: a read-only registry over an OCI layout on IPFS The first piece of fetching everything over IPFS: on the server, Docker pulls the playbook's images from it, and it reads them through the local IPFS gateway. Manifests are checked against the layout's digests. Co-Authored-By: Claude Opus 5.5 --- internal/cli/cli.go | 2 + internal/cli/ipfs.go | 29 +++++++ internal/ipfs/registry.go | 153 +++++++++++++++++++++++++++++++++ internal/ipfs/registry_test.go | 81 +++++++++++++++++ 4 files changed, 265 insertions(+) create mode 100644 internal/cli/ipfs.go create mode 100644 internal/ipfs/registry.go create mode 100644 internal/ipfs/registry_test.go diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b4431e0..e6e030e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -36,6 +36,8 @@ var Commands = map[string]func(args []string) error{ "bundle": Bundle, "unbundle": Unbundle, "mirrors": Mirrors, + + "serve-registry": ServeRegistry, } const Usage = `Usage: diff --git a/internal/cli/ipfs.go b/internal/cli/ipfs.go new file mode 100644 index 0000000..62dc369 --- /dev/null +++ b/internal/cli/ipfs.go @@ -0,0 +1,29 @@ +package cli + +import ( + "flag" + "fmt" + "net/http" + "strings" + + "interzone/internal/ipfs" +) + +// ServeRegistry runs on the server during an IPFS deploy: Docker pulls the +// playbook's images from it, and it reads them through the local gateway. +// interzone starts and stops it; it isn't in Usage. +func ServeRegistry(args []string) error { + fs := flag.NewFlagSet("serve-registry", flag.ExitOnError) + layout := fs.String("layout", "", "URL of the OCI layout, e.g. http://127.0.0.1:8080/ipfs/CID/oci") + listen := fs.String("listen", "127.0.0.1:5050", "address to serve the registry on") + parse(fs, args) + if *layout == "" { + fs.Usage() + return ErrFailed + } + r := &ipfs.Registry{Base: strings.TrimSuffix(*layout, "/"), Client: http.DefaultClient} + if err := r.Load(); err != nil { + return fmt.Errorf("reading the image list: %w", err) + } + return http.ListenAndServe(*listen, r) +} diff --git a/internal/ipfs/registry.go b/internal/ipfs/registry.go new file mode 100644 index 0000000..d9ffc4f --- /dev/null +++ b/internal/ipfs/registry.go @@ -0,0 +1,153 @@ +// Package ipfs fetches what a deploy needs from interzone's IPFS swarm. +package ipfs + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" +) + +// Registry serves an OCI image layout that is reachable over HTTP (an IPFS +// gateway's /ipfs//oci) as a read-only Docker registry, so the +// playbook pulls /: the way it pulls from zot. +type Registry struct { + Base string // URL of the layout's directory, without a trailing slash + Client *http.Client + refs map[string]descriptor // "element-hq/synapse:v1.2" -> its index +} + +type descriptor struct { + MediaType string `json:"mediaType"` + Digest string `json:"digest"` + Size int64 `json:"size"` +} + +var digestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) + +// Load reads the layout's index.json. +func (r *Registry) Load() error { + var idx struct { + Manifests []struct { + descriptor + Annotations map[string]string `json:"annotations"` + } `json:"manifests"` + } + b, err := r.get("index.json", 4<<20) + if err != nil { + return err + } + if err := json.Unmarshal(b, &idx); err != nil { + return fmt.Errorf("index.json: %w", err) + } + r.refs = map[string]descriptor{} + for _, m := range idx.Manifests { + if name := m.Annotations["org.opencontainers.image.ref.name"]; name != "" && digestRe.MatchString(m.Digest) { + r.refs[name] = m.descriptor + } + } + return nil +} + +func (r *Registry) get(path string, limit int64) ([]byte, error) { + res, err := r.Client.Get(r.Base + "/" + path) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%s: %s", path, res.Status) + } + return io.ReadAll(io.LimitReader(res.Body, limit)) +} + +func blobPath(digest string) string { return "blobs/sha256/" + strings.TrimPrefix(digest, "sha256:") } + +func (r *Registry) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet && req.Method != http.MethodHead { + http.Error(w, "read-only", http.StatusMethodNotAllowed) + return + } + p := req.URL.Path + if p == "/v2/" || p == "/v2" { + w.Header().Set("Docker-Distribution-API-Version", "registry/2.0") + return + } + if i := strings.LastIndex(p, "/manifests/"); strings.HasPrefix(p, "/v2/") && i > 3 { + r.manifest(w, req, p[4:i], p[i+len("/manifests/"):]) + return + } + if i := strings.LastIndex(p, "/blobs/"); strings.HasPrefix(p, "/v2/") && i > 3 { + r.blob(w, req, p[i+len("/blobs/"):]) + return + } + http.NotFound(w, req) +} + +func (r *Registry) manifest(w http.ResponseWriter, req *http.Request, name, ref string) { + d, ok := r.refs[name+":"+ref] + if digestRe.MatchString(ref) { + d, ok = descriptor{Digest: ref}, true + } + if !ok { + http.Error(w, `{"errors":[{"code":"MANIFEST_UNKNOWN"}]}`, http.StatusNotFound) + return + } + b, err := r.get(blobPath(d.Digest), 4<<20) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + // The digest comes from the signed index; the bytes from whoever had them. + if sum := sha256.Sum256(b); "sha256:"+hex.EncodeToString(sum[:]) != d.Digest { + http.Error(w, "digest mismatch", http.StatusBadGateway) + return + } + if d.MediaType == "" { + var m struct { + MediaType string `json:"mediaType"` + } + _ = json.Unmarshal(b, &m) + d.MediaType = m.MediaType + } + w.Header().Set("Content-Type", d.MediaType) + w.Header().Set("Docker-Content-Digest", d.Digest) + w.Header().Set("Content-Length", strconv.Itoa(len(b))) + if req.Method == http.MethodGet { + _, _ = w.Write(b) + } +} + +func (r *Registry) blob(w http.ResponseWriter, req *http.Request, digest string) { + if !digestRe.MatchString(digest) { + http.NotFound(w, req) + return + } + up, err := http.NewRequestWithContext(req.Context(), req.Method, r.Base+"/"+blobPath(digest), nil) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + res, err := r.Client.Do(up) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + http.Error(w, res.Status, http.StatusNotFound) + return + } + // Docker checks the blob against its digest itself. + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Docker-Content-Digest", digest) + if res.ContentLength >= 0 { + w.Header().Set("Content-Length", strconv.FormatInt(res.ContentLength, 10)) + } + _, _ = io.Copy(w, res.Body) +} diff --git a/internal/ipfs/registry_test.go b/internal/ipfs/registry_test.go new file mode 100644 index 0000000..59b41a5 --- /dev/null +++ b/internal/ipfs/registry_test.go @@ -0,0 +1,81 @@ +package ipfs + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +func writeBlob(t *testing.T, dir string, b []byte) string { + sum := sha256.Sum256(b) + h := hex.EncodeToString(sum[:]) + if err := os.WriteFile(filepath.Join(dir, "blobs", "sha256", h), b, 0o644); err != nil { + t.Fatal(err) + } + return "sha256:" + h +} + +func TestRegistry(t *testing.T) { + dir := t.TempDir() + os.MkdirAll(filepath.Join(dir, "blobs", "sha256"), 0o755) + layer := writeBlob(t, dir, []byte("layer bytes")) + man := []byte(fmt.Sprintf(`{"mediaType":"application/vnd.oci.image.manifest.v1+json","layers":[{"digest":%q}]}`, layer)) + md := writeBlob(t, dir, man) + bad := "sha256:" + fmt.Sprintf("%064x", 1) + os.WriteFile(filepath.Join(dir, "blobs", "sha256", fmt.Sprintf("%064x", 1)), man, 0o644) // not what its name says + os.WriteFile(filepath.Join(dir, "index.json"), []byte(fmt.Sprintf(`{"manifests":[ + {"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":%q,"size":%d,"annotations":{"org.opencontainers.image.ref.name":"element-hq/synapse:v1"}}, + {"digest":%q,"annotations":{"org.opencontainers.image.ref.name":"evil/tampered:v1"}}]}`, md, len(man), bad)), 0o644) + gw := httptest.NewServer(http.FileServer(http.Dir(dir))) + defer gw.Close() + + r := &Registry{Base: gw.URL, Client: gw.Client()} + if err := r.Load(); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(r) + defer srv.Close() + get := func(method, path string) (*http.Response, string) { + req, _ := http.NewRequest(method, srv.URL+path, nil) + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + return res, string(b) + } + + for _, ref := range []string{"v1", md} { + res, body := get("GET", "/v2/element-hq/synapse/manifests/"+ref) + if res.StatusCode != 200 || body != string(man) || + res.Header.Get("Content-Type") != "application/vnd.oci.image.manifest.v1+json" || res.Header.Get("Docker-Content-Digest") != md { + t.Errorf("manifest %s: %d %q %v", ref, res.StatusCode, body, res.Header) + } + } + if res, body := get("HEAD", "/v2/element-hq/synapse/manifests/v1"); res.StatusCode != 200 || body != "" || res.ContentLength != int64(len(man)) { + t.Errorf("HEAD: %d %q %d", res.StatusCode, body, res.ContentLength) + } + if res, body := get("GET", "/v2/element-hq/synapse/blobs/"+layer); res.StatusCode != 200 || body != "layer bytes" { + t.Errorf("blob: %d %q", res.StatusCode, body) + } + for path, want := range map[string]int{ + "/v2/": 200, + "/v2/element-hq/synapse/manifests/v2": 404, + "/v2/evil/tampered/manifests/v1": 502, // bytes that don't match the index + "/v2/x/blobs/sha256:../../index.json": 404, + } { + if res, _ := get("GET", path); res.StatusCode != want { + t.Errorf("%s: %d, want %d", path, res.StatusCode, want) + } + } + if res, _ := get("PUT", "/v2/element-hq/synapse/manifests/v1"); res.StatusCode != 405 { + t.Errorf("PUT: %d", res.StatusCode) + } +}