1package cli
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "os/exec"
11 "strings"
12
13 cerrdefs "github.com/containerd/errdefs"
14 "github.com/docker/docker/client"
15
16 "github.com/bnema/gordon/internal/adapters/in/cli/remote"
17 "github.com/bnema/gordon/pkg/registrypush"
18)
19
20// pushImageOps abstracts container image operations needed by push commands.
21// The real implementation uses Docker SDK + registrypush; tests inject fakes.
22type pushImageOps interface {
23 // Tag creates a new tag for an existing local image.
24 Tag(ctx context.Context, sourceRef, targetRef string) error
25 // Push uploads a local image to its registry using chunked blob uploads.
26 Push(ctx context.Context, ref string) error
27 // Exists checks whether a local image exists.
28 Exists(ctx context.Context, imageRef string) (bool, error)
29 // Build runs a container image build. Only Docker with buildx is supported;
30 // other runtimes return an actionable error.
31 Build(ctx context.Context, args []string) error
32}
33
34// dockerImageOps implements pushImageOps using the Docker SDK and registrypush.
35type dockerImageOps struct {
36 cli client.APIClient
37 insecureTLS bool
38 progress io.Writer
39 remoteClient *remote.Client // nil when local
40}
41
42// newDockerImageOps creates a dockerImageOps from the Docker environment.
43func newDockerImageOps(insecureTLS bool, progress io.Writer) (*dockerImageOps, error) {
44 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
45 if err != nil {
46 return nil, fmt.Errorf("failed to create Docker client: %w", err)
47 }
48 return &dockerImageOps{
49 cli: cli,
50 insecureTLS: insecureTLS,
51 progress: progress,
52 }, nil
53}
54
55// newImageOpsFromFlags resolves TLS settings from CLI flags/config and creates ops.
56func newImageOpsFromFlags() (pushImageOps, error) {
57 remoteURL, token, insecureTLS, _ := remote.ResolveRemote(remoteFlag, tokenFlag, insecureTLSFlag)
58 ops, err := newDockerImageOps(insecureTLS, os.Stderr)
59 if err != nil {
60 return nil, err
61 }
62 if remoteURL != "" && token != "" {
63 var clientOpts []remote.ClientOption
64 clientOpts = append(clientOpts, remote.WithToken(token))
65 if insecureTLS {
66 clientOpts = append(clientOpts, remote.WithInsecureTLS(true))
67 }
68 ops.remoteClient = remote.NewClient(remoteURL, clientOpts...)
69 }
70 return ops, nil
71}
72
73func (d *dockerImageOps) Tag(ctx context.Context, sourceRef, targetRef string) error {
74 if err := d.cli.ImageTag(ctx, sourceRef, targetRef); err != nil {
75 return fmt.Errorf("failed to tag %s as %s: %w", sourceRef, targetRef, err)
76 }
77 return nil
78}
79
80func (d *dockerImageOps) Push(ctx context.Context, ref string) error {
81 opts := []registrypush.Option{
82 registrypush.WithProgress(d.progress),
83 registrypush.WithInsecureTLS(d.insecureTLS),
84 }
85
86 if d.remoteClient != nil {
87 authHeader, err := d.exchangeRegistryAuth(ctx)
88 if err != nil {
89 return fmt.Errorf("failed to obtain registry credentials: %w", err)
90 }
91 opts = append(opts, registrypush.WithAuth(authHeader))
92
93 pusher := registrypush.New(opts...)
94 err = pusher.Push(ctx, ref)
95 if err != nil && isAuthError(err) {
96 // Token may have expired mid-push; refresh once and retry.
97 authHeader, refreshErr := d.exchangeRegistryAuth(ctx)
98 if refreshErr != nil {
99 return fmt.Errorf("failed to refresh registry credentials after auth error: %w (original: %v)", refreshErr, err)
100 }
101 retryOpts := []registrypush.Option{
102 registrypush.WithProgress(d.progress),
103 registrypush.WithInsecureTLS(d.insecureTLS),
104 registrypush.WithAuth(authHeader),
105 }
106 pusher = registrypush.New(retryOpts...)
107 return pusher.Push(ctx, ref)
108 }
109 return err
110 }
111
112 pusher := registrypush.New(opts...)
113 return pusher.Push(ctx, ref)
114}
115
116// isAuthError returns true if the error indicates an HTTP 401 authentication failure.
117// Prefers typed HTTPError from the remote client; falls back to string matching for
118// errors from registrypush which uses its own error format.
119func isAuthError(err error) bool {
120 if err == nil {
121 return false
122 }
123 var httpErr *remote.HTTPError
124 if errors.As(err, &httpErr) {
125 return httpErr.StatusCode == http.StatusUnauthorized
126 }
127 msg := err.Error()
128 return strings.Contains(msg, "status 401") || strings.Contains(msg, "401 Unauthorized")
129}
130
131// exchangeRegistryAuth exchanges the long-lived Gordon token for a short-lived
132// registry access token. Returns the Authorization header value (e.g. "Bearer <token>").
133func (d *dockerImageOps) exchangeRegistryAuth(ctx context.Context) (string, error) {
134 // Step 1: Get subject from server (validates token is still active)
135 verifyResp, err := d.remoteClient.VerifyAuth(ctx)
136 if err != nil {
137 return "", fmt.Errorf("failed to verify token: %w", err)
138 }
139 if !verifyResp.Valid {
140 return "", fmt.Errorf("token is not valid")
141 }
142 if verifyResp.Subject == "" {
143 return "", fmt.Errorf("empty subject in verified token")
144 }
145
146 // Step 2: Exchange long-lived token for short-lived registry token
147 shortToken, err := d.remoteClient.ExchangeRegistryToken(ctx, verifyResp.Subject)
148 if err != nil {
149 return "", fmt.Errorf("failed to exchange registry token: %w", err)
150 }
151
152 return "Bearer " + shortToken, nil
153}
154
155func (d *dockerImageOps) Exists(ctx context.Context, imageRef string) (bool, error) {
156 _, err := d.cli.ImageInspect(ctx, imageRef)
157 if err != nil {
158 if cerrdefs.IsNotFound(err) {
159 return false, nil
160 }
161 return false, fmt.Errorf("failed to inspect image %s: %w", imageRef, err)
162 }
163 return true, nil
164}
165
166func (d *dockerImageOps) Build(ctx context.Context, args []string) error {
167 if _, err := exec.LookPath("docker"); err != nil {
168 return fmt.Errorf(
169 "image build requires Docker with buildx\n\n" +
170 "Podman and other runtimes are not supported for --build.\n" +
171 "Build the image manually and push with:\n" +
172 " podman build -t <image> .\n" +
173 " gordon push <image>",
174 )
175 }
176 cmd := exec.CommandContext(ctx, "docker", args...) // #nosec G204
177 cmd.Env = os.Environ()
178 cmd.Stdout = os.Stdout
179 cmd.Stderr = os.Stderr
180 if err := cmd.Run(); err != nil {
181 return fmt.Errorf("docker buildx build failed: %w", err)
182 }
183 return nil
184}