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