Repository navigation
Expand file tree
/
Copy pathclient_methods.go
More file actions
334 lines (286 loc) · 9.76 KB
/
Copy pathclient_methods.go
File metadata and controls
334 lines (286 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2026 Columnar Technologies Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbc
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/columnar-tech/dbc/auth"
"github.com/columnar-tech/dbc/config"
"github.com/go-faster/yaml"
)
func (c *Client) makeRequest(ctx context.Context, u string) (*http.Response, error) {
uri, err := url.Parse(u)
if err != nil {
return nil, fmt.Errorf("failed to parse URL %s: %w", u, err)
}
// Replaced requests are anonymous: no credentials, no telemetry ids.
eff, replaced, err := c.router.route(uri)
if err != nil {
return nil, err
}
if replaced {
return anonymousGet(ctx, c.httpClient, c.router, eff, uri.Path)
}
c.setup()
// A redirect must not reach an origin that a rule replaces either.
hc := c.router.guardRedirects(c.httpClient, false)
cred, err := c.getCredential(uri)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to read credentials: %w", err)
}
q := uri.Query()
q.Add("mid", c.mid)
q.Add("uid", c.uid.String())
uri.RawQuery = q.Encode()
buildReq := func(token string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri.String(), nil)
if err != nil {
return nil, err
}
if uri.Path == "/index.yaml" {
req.Header.Set("Accept", "application/yaml")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
return req, nil
}
token := ""
if cred != nil {
if auth.IsColumnarPrivateRegistry(uri) {
_ = auth.FetchColumnarLicense(ctx, cred)
}
token = cred.GetAuthToken(ctx)
}
req, err := buildReq(token)
if err != nil {
return nil, fmt.Errorf("failed to build request: %w", err)
}
resp, err := hc.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized && cred != nil {
resp.Body.Close()
if err := cred.RefreshAndPersist(ctx); err != nil {
return nil, fmt.Errorf("failed to refresh auth token: %w", err)
}
req, err = buildReq(cred.GetAuthToken(ctx))
if err != nil {
return nil, fmt.Errorf("failed to build retry request: %w", err)
}
resp, err = hc.Do(req)
if err != nil {
return nil, err
}
}
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
err = ErrUnauthorized
if auth.IsColumnarPrivateRegistry(uri) && cred != nil {
err = ErrUnauthorizedColumnar
}
resp.Body.Close()
return nil, fmt.Errorf("%s%s: %w", uri.Host, uri.Path, err)
}
return resp, nil
}
func (c *Client) getDriverListFromIndex(ctx context.Context, index *Registry) ([]Driver, error) {
resp, err := c.makeRequest(ctx, index.BaseURL.JoinPath("/index.yaml").String())
if err != nil {
return nil, fmt.Errorf("failed to fetch drivers: %w", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("failed to fetch drivers: %s", resp.Status)
}
defer resp.Body.Close()
drivers := struct {
Name string `yaml:"name"`
Drivers []Driver `yaml:"drivers"`
}{}
if err = yaml.NewDecoder(resp.Body).Decode(&drivers); err != nil {
return nil, fmt.Errorf("failed to parse driver registry index: %s", err)
}
if drivers.Name != "" {
index.Name = drivers.Name
}
for i := range drivers.Drivers {
drivers.Drivers[i].Registry = index
}
result := drivers.Drivers
sort.Slice(result, func(i, j int) bool {
return result[i].Path < result[j].Path
})
return result, nil
}
// Search searches for drivers matching the given pattern across all registries.
func (c *Client) Search(ctx context.Context, pattern string) ([]Driver, error) {
var (
allDrivers []Driver
errs []error
)
for i := range c.registries {
drivers, err := c.getDriverListFromIndex(ctx, &c.registries[i])
if err != nil {
errs = append(errs, fmt.Errorf("registry %s: %w", c.registries[i].BaseURL, err))
continue
}
c.registries[i].Drivers = drivers
allDrivers = append(allDrivers, drivers...)
}
// One joined error per failed registry.
totalErr := errors.Join(errs...)
if pattern == "" {
return allDrivers, totalErr
}
lowerPattern := strings.ToLower(pattern)
var filtered []Driver
for _, d := range allDrivers {
if strings.Contains(strings.ToLower(d.Path), lowerPattern) ||
strings.Contains(strings.ToLower(d.Title), lowerPattern) {
filtered = append(filtered, d)
}
}
return filtered, totalErr
}
func (c *Client) downloadPackage(ctx context.Context, pkg PkgInfo) (*os.File, error) {
if pkg.Path == nil {
return nil, fmt.Errorf("cannot download package for %s: no url set", pkg.Driver.Title)
}
location := pkg.Path.String()
rsp, err := c.makeRequest(ctx, location)
if err != nil {
return nil, fmt.Errorf("failed to download driver: %w", err)
}
if rsp.StatusCode != http.StatusOK {
rsp.Body.Close()
return nil, fmt.Errorf("failed to download driver %s: %s", location, rsp.Status)
}
defer rsp.Body.Close()
// Name the file after the escaped URL path only: a query (for example a
// registry token) must not end up in the file name, and decoding could
// turn %5C into a Windows path separator.
fname := path.Base(pkg.Path.EscapedPath())
tmpdir, err := os.MkdirTemp(os.TempDir(), "adbc-drivers-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
var output *os.File
defer func() {
if output == nil {
os.RemoveAll(tmpdir)
}
}()
output, err = os.Create(path.Join(tmpdir, fname))
if err != nil {
return nil, fmt.Errorf("failed to create temp file to download to: %w", err)
}
if _, err = io.Copy(output, rsp.Body); err != nil {
output.Close()
output = nil
return nil, fmt.Errorf("failed to write driver file: %w", err)
}
return output, nil
}
// Download fetches the tarball for pkg and returns its contents as an
// io.ReadCloser. The caller is responsible for closing the returned body.
// Auth credentials are resolved and injected automatically, including token
// refresh on 401.
func (c *Client) Download(ctx context.Context, pkg PkgInfo) (io.ReadCloser, error) {
if pkg.Path == nil {
return nil, fmt.Errorf("cannot download package for %s: no url set", pkg.Driver.Title)
}
rsp, err := c.makeRequest(ctx, pkg.Path.String())
if err != nil {
return nil, fmt.Errorf("failed to download %s: %w", pkg.Path, err)
}
if rsp.StatusCode != http.StatusOK {
defer rsp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(rsp.Body, 1024))
if len(body) > 0 {
return nil, fmt.Errorf("failed to download %s: %s: %s", pkg.Path, rsp.Status, body)
}
return nil, fmt.Errorf("failed to download %s: %s", pkg.Path, rsp.Status)
}
return rsp.Body, nil
}
// InstallOption configures Client.Install.
type InstallOption func(*installOptions)
type installOptions struct{ allowUnsigned bool }
// AllowUnsigned makes Client.Install skip signature verification, like the
// CLI's --no-verify. Use it only for drivers from a trusted private registry.
func AllowUnsigned() InstallOption {
return func(o *installOptions) { o.allowUnsigned = true }
}
// Install installs a driver with the given name to the specified
// configuration, verifying its signature with VerifyPackageSignature (which
// checks the driver library's Columnar signature) unless
// AllowUnsigned is given. When the registry publishes a SHA-256 for the
// package, the downloaded archive must match it even with AllowUnsigned.
// Verification runs on the staged package before it is
// published, so a driver that fails it leaves any existing install in place.
func (c *Client) Install(ctx context.Context, cfg config.Config, driverName string, opts ...InstallOption) (*config.Manifest, error) {
var o installOptions
for _, opt := range opts {
opt(&o)
}
drivers, err := c.Search(ctx, driverName)
// Only fail if the driver wasn't found in any registry; partial registry errors
// are acceptable as long as we can still locate the target driver.
if err != nil && len(drivers) == 0 {
return nil, fmt.Errorf("failed to search for driver %s: %w", driverName, err)
}
pkg, err := ResolvePackage(drivers, driverName, func(d *Driver) (PkgInfo, error) { return d.GetLatestPackage(config.PlatformTuple(), false) })
if err != nil {
return nil, fmt.Errorf("failed to get package for driver %s: %w", driverName, err)
}
f, err := c.downloadPackage(ctx, pkg)
if err != nil {
return nil, fmt.Errorf("failed to download driver %s: %w", driverName, err)
}
defer os.RemoveAll(filepath.Dir(f.Name()))
installOpts := config.InstallPackageOptions{ExpectedArchiveSHA256: pkg.ArchiveSHA256}
if !o.allowUnsigned {
// VerifyPackageSignature checks the driver library's Columnar signature.
installOpts.SignatureVerifier = VerifyPackageSignature
}
manifest, err := config.InstallPackage(ctx, cfg, driverName, f, installOpts)
if err != nil {
return nil, fmt.Errorf("failed to install driver %s: %w", driverName, err)
}
return &manifest, nil
}
// Uninstall removes a driver's runtime registration from the specified
// configuration. For external registrations, the shared library remains in
// place because dbc does not own it.
func (c *Client) Uninstall(cfg config.Config, driverName string) error {
di, err := config.GetDriver(cfg, driverName)
if err != nil {
return fmt.Errorf("failed to find driver %q: %w", driverName, err)
}
if err := config.UninstallDriver(cfg, di); err != nil {
return fmt.Errorf("failed to uninstall driver %q: %w", driverName, err)
}
return nil
}