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 resolved, _ := remote.Resolve(remoteFlag, tokenFlag, insecureTLSFlag)
58 return newImageOpsForResolvedRemote(resolved)
59}
60
61func newImageOpsForResolvedRemote(resolved *remote.ResolvedRemote) (pushImageOps, error) {
62 insecureTLS := false
63 if resolved != nil {
64 insecureTLS = resolved.InsecureTLS
65 }
66 ops, err := newDockerImageOps(insecureTLS, os.Stderr)
67 if err != nil {
68 return nil, err
69 }
70 if resolved != nil && resolved.Token != "" {
71 ops.remoteClient = remote.NewClient(resolved.URL, remoteClientOptions(resolved.Token, resolved.InsecureTLS)...)
72 }
73 return ops, nil
74}
75
76func (d *dockerImageOps) Tag(ctx context.Context, sourceRef, targetRef string) error {
77 if err := d.cli.ImageTag(ctx, sourceRef, targetRef); err != nil {
78 return fmt.Errorf("failed to tag %s as %s: %w", sourceRef, targetRef, err)
79 }
80 return nil
81}
82
83func (d *dockerImageOps) Push(ctx context.Context, ref string) error {
84 opts := []registrypush.Option{
85 registrypush.WithProgress(d.progress),
86 registrypush.WithInsecureTLS(d.insecureTLS),
87 }
88
89 if d.remoteClient != nil {
90 authHeader, err := d.exchangeRegistryAuth(ctx)
91 if err != nil {
92 return fmt.Errorf("failed to obtain registry credentials: %w", err)
93 }
94 opts = append(opts, registrypush.WithAuth(authHeader))
95
96 pusher := registrypush.New(opts...)
97 err = pusher.Push(ctx, ref)
98 if err != nil && isAuthError(err) {
99 // Token may have expired mid-push; refresh once and retry.
100 authHeader, refreshErr := d.exchangeRegistryAuth(ctx)
101 if refreshErr != nil {
102 return fmt.Errorf("failed to refresh registry credentials after auth error: %w (original: %v)", refreshErr, err)
103 }
104 retryOpts := []registrypush.Option{
105 registrypush.WithProgress(d.progress),
106 registrypush.WithInsecureTLS(d.insecureTLS),
107 registrypush.WithAuth(authHeader),
108 }
109 pusher = registrypush.New(retryOpts...)
110 return pusher.Push(ctx, ref)
111 }
112 return err
113 }
114
115 pusher := registrypush.New(opts...)
116 return pusher.Push(ctx, ref)
117}
118
119// isAuthError returns true if the error indicates an HTTP 401 authentication failure.
120// Prefers typed HTTPError from the remote client; falls back to string matching for
121// errors from registrypush which uses its own error format.
122func isAuthError(err error) bool {
123 if err == nil {
124 return false
125 }
126 if httpErr, ok := errors.AsType[*remote.HTTPError](err); ok {
127 return httpErr.StatusCode == http.StatusUnauthorized
128 }
129 msg := err.Error()
130 return strings.Contains(msg, "status 401") || strings.Contains(msg, "401 Unauthorized")
131}
132
133// exchangeRegistryAuth exchanges the long-lived Gordon token for a short-lived
134// registry access token. Returns the Authorization header value (e.g. "Bearer <token>").
135func (d *dockerImageOps) exchangeRegistryAuth(ctx context.Context) (string, error) {
136 // Step 1: Get subject from server (validates token is still active)
137 verifyResp, err := d.remoteClient.VerifyAuth(ctx)
138 if err != nil {
139 return "", fmt.Errorf("failed to verify token: %w", err)
140 }
141 if !verifyResp.Valid {
142 return "", fmt.Errorf("token is not valid")
143 }
144 if verifyResp.Subject == "" {
145 return "", fmt.Errorf("empty subject in verified token")
146 }
147
148 // Step 2: Exchange long-lived token for short-lived registry token
149 shortToken, err := d.remoteClient.ExchangeRegistryToken(ctx, verifyResp.Subject)
150 if err != nil {
151 return "", fmt.Errorf("failed to exchange registry token: %w", err)
152 }
153
154 return "Bearer " + shortToken, nil
155}
156
157func (d *dockerImageOps) Exists(ctx context.Context, imageRef string) (bool, error) {
158 _, err := d.cli.ImageInspect(ctx, imageRef)
159 if err != nil {
160 if cerrdefs.IsNotFound(err) {
161 return false, nil
162 }
163 return false, fmt.Errorf("failed to inspect image %s: %w", imageRef, err)
164 }
165 return true, nil
166}
167
168func (d *dockerImageOps) Build(ctx context.Context, args []string) error {
169 if _, err := exec.LookPath("docker"); err != nil {
170 return fmt.Errorf(
171 "image build requires Docker with buildx\n\n" +
172 "Podman and other runtimes are not supported for --build.\n" +
173 "Build the image manually and push with:\n" +
174 " podman build -t <image> .\n" +
175 " gordon push <image>",
176 )
177 }
178 cmd := exec.CommandContext(ctx, "docker", args...) // #nosec G204
179 cmd.Env = os.Environ()
180 cmd.Stdout = os.Stdout
181 cmd.Stderr = os.Stderr
182 if err := cmd.Run(); err != nil {
183 return fmt.Errorf("docker buildx build failed: %w", err)
184 }
185 return nil
186}