|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/sha256" |
| 5 | + "encoding/hex" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net" |
| 10 | + "net/http" |
| 11 | + "net/http/httptest" |
| 12 | + "path/filepath" |
| 13 | + "slices" |
| 14 | + "strings" |
| 15 | + "sync" |
| 16 | + "testing" |
| 17 | + |
| 18 | + coreerrors "github.com/devcontainers/cli/internal/errors" |
| 19 | + "github.com/devcontainers/cli/internal/log" |
| 20 | + "github.com/devcontainers/cli/internal/oci" |
| 21 | +) |
| 22 | + |
| 23 | +type pushRegistry struct { |
| 24 | + host string |
| 25 | + failTag string |
| 26 | + |
| 27 | + mu sync.Mutex |
| 28 | + blobs map[string][]byte |
| 29 | + manifests map[string][]byte |
| 30 | + attempts map[string][]string |
| 31 | +} |
| 32 | + |
| 33 | +func newPushRegistry(t *testing.T, failTag string) *pushRegistry { |
| 34 | + t.Helper() |
| 35 | + r := &pushRegistry{failTag: failTag, blobs: map[string][]byte{}, manifests: map[string][]byte{}, attempts: map[string][]string{}} |
| 36 | + srv := httptest.NewServer(http.HandlerFunc(r.serve)) |
| 37 | + t.Cleanup(srv.Close) |
| 38 | + // A localhost registry is plain HTTP for both CLIs. |
| 39 | + _, port, err := net.SplitHostPort(srv.Listener.Addr().String()) |
| 40 | + if err != nil { |
| 41 | + t.Fatal(err) |
| 42 | + } |
| 43 | + r.host = "localhost:" + port |
| 44 | + return r |
| 45 | +} |
| 46 | + |
| 47 | +func (r *pushRegistry) tagAttempts(repo string) []string { |
| 48 | + r.mu.Lock() |
| 49 | + defer r.mu.Unlock() |
| 50 | + return slices.Clone(r.attempts[repo]) |
| 51 | +} |
| 52 | + |
| 53 | +func (r *pushRegistry) serve(w http.ResponseWriter, req *http.Request) { |
| 54 | + r.mu.Lock() |
| 55 | + defer r.mu.Unlock() |
| 56 | + path := strings.TrimPrefix(req.URL.Path, "/v2/") |
| 57 | + notFound := func() { |
| 58 | + w.Header().Set("Content-Type", "application/json") |
| 59 | + w.WriteHeader(http.StatusNotFound) |
| 60 | + _, _ = w.Write([]byte(`{"errors":[{"code":"NAME_UNKNOWN","message":"not found"}]}`)) |
| 61 | + } |
| 62 | + switch { |
| 63 | + case path == "" || path == "/": |
| 64 | + w.WriteHeader(http.StatusOK) |
| 65 | + case strings.HasSuffix(path, "/tags/list"): |
| 66 | + notFound() |
| 67 | + case strings.Contains(path, "/blobs/uploads/") && req.Method == http.MethodPost: |
| 68 | + w.Header().Set("Location", req.URL.Path+"session") |
| 69 | + w.WriteHeader(http.StatusAccepted) |
| 70 | + case strings.Contains(path, "/blobs/uploads/") && req.Method == http.MethodPut: |
| 71 | + body, _ := io.ReadAll(req.Body) |
| 72 | + digest := req.URL.Query().Get("digest") |
| 73 | + r.blobs[digest] = body |
| 74 | + w.Header().Set("Docker-Content-Digest", digest) |
| 75 | + w.WriteHeader(http.StatusCreated) |
| 76 | + case strings.Contains(path, "/blobs/"): |
| 77 | + body, ok := r.blobs[path[strings.LastIndex(path, "/")+1:]] |
| 78 | + if !ok { |
| 79 | + notFound() |
| 80 | + return |
| 81 | + } |
| 82 | + w.Header().Set("Content-Length", fmt.Sprint(len(body))) |
| 83 | + if req.Method != http.MethodHead { |
| 84 | + _, _ = w.Write(body) |
| 85 | + } |
| 86 | + case strings.Contains(path, "/manifests/"): |
| 87 | + i := strings.Index(path, "/manifests/") |
| 88 | + repo, ref := path[:i], path[i+len("/manifests/"):] |
| 89 | + if req.Method != http.MethodPut { |
| 90 | + body, ok := r.manifests[repo+":"+ref] |
| 91 | + if !ok { |
| 92 | + notFound() |
| 93 | + return |
| 94 | + } |
| 95 | + w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json") |
| 96 | + w.Header().Set("Content-Length", fmt.Sprint(len(body))) |
| 97 | + if req.Method != http.MethodHead { |
| 98 | + _, _ = w.Write(body) |
| 99 | + } |
| 100 | + return |
| 101 | + } |
| 102 | + r.attempts[repo] = append(r.attempts[repo], ref) |
| 103 | + if ref == r.failTag { |
| 104 | + w.Header().Set("Content-Type", "application/json") |
| 105 | + w.WriteHeader(http.StatusBadRequest) |
| 106 | + _, _ = w.Write([]byte(`{"errors":[{"code":"TAG_INVALID","message":"tag rejected by test"}]}`)) |
| 107 | + return |
| 108 | + } |
| 109 | + body, _ := io.ReadAll(req.Body) |
| 110 | + r.manifests[repo+":"+ref] = body |
| 111 | + sum := sha256.Sum256(body) |
| 112 | + w.Header().Set("Docker-Content-Digest", "sha256:"+hex.EncodeToString(sum[:])) |
| 113 | + w.WriteHeader(http.StatusCreated) |
| 114 | + default: |
| 115 | + notFound() |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +func writeTagFailureCollection(t *testing.T, collectionType string) string { |
| 120 | + t.Helper() |
| 121 | + src := filepath.Join(t.TempDir(), "src") |
| 122 | + if collectionType == "feature" { |
| 123 | + writeSeamFeature(t, src, "good", "1.0.0") |
| 124 | + return src |
| 125 | + } |
| 126 | + writeFile(t, filepath.Join(src, "good", "devcontainer-template.json"), `{"id":"good","version":"1.0.0","name":"Good"}`, 0o644) |
| 127 | + writeFile(t, filepath.Join(src, "good", ".devcontainer.json"), `{"image":"alpine"}`, 0o644) |
| 128 | + return src |
| 129 | +} |
| 130 | + |
| 131 | +func TestPublishCollection_FailedTagPushExits(t *testing.T) { |
| 132 | + for _, collectionType := range []string{"feature", "template"} { |
| 133 | + t.Run(collectionType, func(t *testing.T) { |
| 134 | + reg := newPushRegistry(t, "1.0") |
| 135 | + out := &captureOutput{} |
| 136 | + logger := log.New(log.Options{Level: log.LevelInfo, Format: "text", Writer: out.Stderr()}) |
| 137 | + client := oci.NewClientWithAuthPolicy(logger, map[string]string{"DOCKER_CONFIG": t.TempDir()}, oci.DefaultAuthPolicy()) |
| 138 | + |
| 139 | + err := publishCollectionWith(t.Context(), out, client, writeTagFailureCollection(t, collectionType), reg.host, "me/coll", collectionType, "info") |
| 140 | + if exit, ok := errors.AsType[*coreerrors.ExitCodeError](err); !ok || exit.Code != 1 { |
| 141 | + t.Fatalf("err = %v, want exit code 1 after the rejected tag", err) |
| 142 | + } |
| 143 | + if out.out.Len() != 0 { |
| 144 | + t.Errorf("stdout = %q, want no result after a failed tag push", out.out.String()) |
| 145 | + } |
| 146 | + |
| 147 | + resource := reg.host + "/me/coll/good" |
| 148 | + stderr := out.err.String() |
| 149 | + for _, want := range []string{ |
| 150 | + "Failed to PUT manifest for tag 1.0\n", |
| 151 | + fmt.Sprintf("(!) ERR: Failed to publish %s: '%s'", collectionType, resource), |
| 152 | + fmt.Sprintf("(!) ERR: Failed to publish '%s'", resource), |
| 153 | + } { |
| 154 | + if !strings.Contains(stderr, want) { |
| 155 | + t.Errorf("stderr is missing %q:\n%s", want, stderr) |
| 156 | + } |
| 157 | + } |
| 158 | + if strings.Contains(stderr, "Published "+collectionType) { |
| 159 | + t.Errorf("stderr reports a successful publish:\n%s", stderr) |
| 160 | + } |
| 161 | + |
| 162 | + if got, want := reg.tagAttempts("me/coll/good"), []string{"1", "1.0"}; !slices.Equal(got, want) { |
| 163 | + t.Errorf("tag PUTs = %v, want %v: no tag is tried after the first failure", got, want) |
| 164 | + } |
| 165 | + if got := reg.tagAttempts("me/coll"); len(got) != 0 { |
| 166 | + t.Errorf("collection metadata PUTs = %v, want none after a failed publish", got) |
| 167 | + } |
| 168 | + }) |
| 169 | + } |
| 170 | +} |
0 commit comments