1package remote
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "os"
11
12 "github.com/bnema/gordon/internal/adapters/dto"
13)
14
15// PasswordRequest represents the request body for POST /auth/password.
16type PasswordRequest struct {
17 Username string `json:"username"`
18 Password string `json:"password"` //nolint:gosec // intentional: CLI credential DTO for auth endpoint
19}
20
21// PasswordResponse represents the response from POST /auth/password.
22type PasswordResponse struct {
23 Token string `json:"token"`
24 ExpiresIn int `json:"expires_in"`
25 IssuedAt string `json:"issued_at"`
26}
27
28// Authenticate calls POST /auth/password and returns a token.
29// This method does NOT require an existing token since it's used to obtain one.
30func (c *Client) Authenticate(ctx context.Context, username, password string) (*PasswordResponse, error) {
31 url := c.baseURL + "/auth/password"
32
33 reqBody := PasswordRequest{
34 Username: username,
35 Password: password,
36 }
37
38 jsonBody, err := json.Marshal(reqBody)
39 if err != nil {
40 return nil, fmt.Errorf("failed to marshal request body: %w", err)
41 }
42
43 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonBody))
44 if err != nil {
45 return nil, fmt.Errorf("failed to create request: %w", err)
46 }
47
48 req.Header.Set("Content-Type", "application/json")
49 req.Header.Set("Accept", "application/json")
50
51 resp, err := c.httpClient.Do(req)
52 if err != nil {
53 return nil, fmt.Errorf("failed to connect: %w", err)
54 }
55 defer resp.Body.Close()
56
57 if resp.StatusCode >= 400 {
58 body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
59 var errResp struct {
60 Error string `json:"error"`
61 }
62 if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
63 return nil, fmt.Errorf("%s: %s", resp.Status, errResp.Error)
64 }
65 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
66 }
67
68 var result PasswordResponse
69 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
70 return nil, fmt.Errorf("failed to decode response: %w", err)
71 }
72
73 return &result, nil
74}
75
76// ExchangeRegistryToken exchanges the client's long-lived Gordon token for a
77// short-lived registry access token via the Docker v2 token endpoint.
78// The subject must match the token's sub claim (use VerifyAuth to obtain it).
79// Returns the raw short-lived token string (without a "Bearer " prefix).
80func (c *Client) ExchangeRegistryToken(ctx context.Context, subject string) (string, error) {
81 // Wildcard scope (repository:*:push,pull) grants push/pull to all repositories.
82 // The server downsopes this to the parent token's actual scopes during exchange.
83 url := c.baseURL + "/auth/token?scope=repository:*:push,pull&service=gordon-registry"
84
85 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
86 if err != nil {
87 return "", fmt.Errorf("failed to create request: %w", err)
88 }
89
90 req.SetBasicAuth(subject, c.token)
91 req.Header.Set("Accept", "application/json")
92
93 resp, err := c.httpClient.Do(req)
94 if err != nil {
95 return "", fmt.Errorf("failed to connect: %w", err)
96 }
97 defer resp.Body.Close()
98
99 if resp.StatusCode >= 400 {
100 body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
101 var errResp struct {
102 Error string `json:"error"`
103 }
104 if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
105 return "", fmt.Errorf("%s: %s", resp.Status, errResp.Error)
106 }
107 return "", fmt.Errorf("%s: %s", resp.Status, string(body))
108 }
109
110 var result dto.TokenResponse
111 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
112 return "", fmt.Errorf("failed to decode response: %w", err)
113 }
114
115 token := result.Token
116 if token == "" {
117 token = result.AccessToken
118 }
119 if token == "" {
120 return "", fmt.Errorf("registry token exchange returned empty token")
121 }
122
123 return token, nil
124}
125
126// UpdateRemoteToken updates the token for a named remote.
127func UpdateRemoteToken(name, token string) error {
128 // Try pass first
129 if passAvailable() {
130 if err := passWriteToken(name, token); err == nil {
131 // Successfully stored in pass. Remove plaintext token from TOML (best-effort).
132 config, err := LoadRemotes("")
133 if err != nil {
134 return nil
135 }
136 remote, ok := config.Remotes[name]
137 if !ok {
138 return nil
139 }
140 remote.Token = ""
141 remote.TokenEnv = ""
142 config.Remotes[name] = remote
143 _ = SaveRemotes("", config)
144 return nil
145 } else {
146 fmt.Fprintf(os.Stderr, "Warning: failed to store token in pass: %v. Falling back to plaintext config.\n", err)
147 }
148 } else {
149 warnPassUnavailable()
150 }
151
152 config, err := LoadRemotes("")
153 if err != nil {
154 return err
155 }
156
157 remote, ok := config.Remotes[name]
158 if !ok {
159 return fmt.Errorf("remote '%s' not found", name)
160 }
161
162 remote.Token = token
163 remote.TokenEnv = "" // Clear token_env when setting token directly
164 config.Remotes[name] = remote
165
166 return SaveRemotes("", config)
167}