/
modconfig.go
327 lines (293 loc) · 9.8 KB
/
modconfig.go
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
// Package modconfig provides access to the standard CUE
// module configuration, including registry access and authorization.
package modconfig
import (
"context"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"strings"
"sync"
"cuelabs.dev/go/oci/ociregistry"
"cuelabs.dev/go/oci/ociregistry/ociauth"
"cuelabs.dev/go/oci/ociregistry/ociclient"
"golang.org/x/oauth2"
"cuelang.org/go/internal/cueconfig"
"cuelang.org/go/internal/cueversion"
"cuelang.org/go/internal/mod/modload"
"cuelang.org/go/internal/mod/modresolve"
"cuelang.org/go/mod/modcache"
"cuelang.org/go/mod/modregistry"
"cuelang.org/go/mod/module"
)
// Registry is used to access CUE modules from external sources.
type Registry interface {
// Requirements returns a list of the modules required by the given module
// version.
Requirements(ctx context.Context, m module.Version) ([]module.Version, error)
// Fetch returns the location of the contents for the given module
// version, downloading it if necessary.
Fetch(ctx context.Context, m module.Version) (module.SourceLoc, error)
// ModuleVersions returns all the versions for the module with the
// given path, which should contain a major version.
ModuleVersions(ctx context.Context, mpath string) ([]string, error)
}
// We don't want to make modload part of the cue/load API,
// so we define the above type independently, but we want
// it to be interchangeable, so check that statically here.
var (
_ Registry = modload.Registry(nil)
_ modload.Registry = Registry(nil)
)
// DefaultRegistry is the default registry host.
const DefaultRegistry = "registry.cue.works"
// Resolver implements [modregistry.Resolver] in terms of the
// CUE registry configuration file and auth configuration.
type Resolver struct {
resolver modresolve.LocationResolver
newRegistry func(host string, insecure bool) (ociregistry.Interface, error)
mu sync.Mutex
registries map[string]ociregistry.Interface
}
// Config provides the starting point for the configuration.
type Config struct {
// TODO allow for a custom resolver to be passed in.
// Transport is used to make the underlying HTTP requests.
// If it's nil, [http.DefaultTransport] will be used.
Transport http.RoundTripper
// Env provides environment variable values. If this is nil,
// the current process's environment will be used.
Env []string
// ClientType is used as part of the User-Agent header
// that's added in each outgoing HTTP request.
// If it's empty, it defaults to "cuelang.org/go".
ClientType string
}
// NewResolver returns an implementation of [modregistry.Resolver]
// that uses cfg to guide registry resolution. If cfg is nil, it's
// equivalent to passing pointer to a zero Config struct.
//
// It consults the same environment variables used by the
// cue command.
//
// The contents of the configuration will not be mutated.
func NewResolver(cfg *Config) (*Resolver, error) {
cfg = newRef(cfg)
cfg.Transport = cueversion.NewTransport(cfg.ClientType, cfg.Transport)
getenv := getenvFunc(cfg.Env)
var configData []byte
var configPath string
cueRegistry := getenv("CUE_REGISTRY")
kind, rest, _ := strings.Cut(cueRegistry, ":")
switch kind {
case "file":
data, err := os.ReadFile(rest)
if err != nil {
return nil, err
}
configData, configPath = data, rest
case "inline":
configData, configPath = []byte(rest), "$CUE_REGISTRY"
case "simple":
cueRegistry = rest
}
var resolver modresolve.LocationResolver
var err error
if configPath != "" {
resolver, err = modresolve.ParseConfig(configData, configPath, DefaultRegistry)
} else {
resolver, err = modresolve.ParseCUERegistry(cueRegistry, DefaultRegistry)
}
if err != nil {
return nil, fmt.Errorf("bad value for $CUE_REGISTRY: %v", err)
}
return &Resolver{
resolver: resolver,
newRegistry: func(host string, insecure bool) (ociregistry.Interface, error) {
return ociclient.New(host, &ociclient.Options{
Insecure: insecure,
Transport: &cueLoginsTransport{
getenv: getenv,
cfg: cfg,
},
})
},
registries: make(map[string]ociregistry.Interface),
}, nil
}
// Host represents a registry host name and whether
// it should be accessed via a secure connection or not.
type Host = modresolve.Host
// AllHosts returns all the registry hosts that the resolver might resolve to,
// ordered lexically by hostname.
func (r *Resolver) AllHosts() []Host {
return r.resolver.AllHosts()
}
// HostLocation represents a registry host and a location with it.
type HostLocation = modresolve.Location
// ResolveToLocation returns the host location for the given module path and version
// without creating a Registry instance for it.
func (r *Resolver) ResolveToLocation(mpath string, version string) (HostLocation, bool) {
return r.resolver.ResolveToLocation(mpath, version)
}
// Resolve implements modregistry.Resolver.Resolve.
func (r *Resolver) ResolveToRegistry(mpath string, version string) (modregistry.RegistryLocation, error) {
loc, ok := r.resolver.ResolveToLocation(mpath, version)
if !ok {
// This can only happen when mpath is invalid, which should not
// happen in practice, as the only caller is modregistry which
// vets module paths before calling Resolve.
return modregistry.RegistryLocation{}, fmt.Errorf("cannot resolve %s (version %s) to registry", mpath, version)
}
r.mu.Lock()
defer r.mu.Unlock()
reg := r.registries[loc.Host]
if reg == nil {
reg1, err := r.newRegistry(loc.Host, loc.Insecure)
if err != nil {
return modregistry.RegistryLocation{}, fmt.Errorf("cannot make client: %v", err)
}
r.registries[loc.Host] = reg1
reg = reg1
}
return modregistry.RegistryLocation{
Registry: reg,
Repository: loc.Repository,
Tag: loc.Tag,
}, nil
}
// cueLoginsTransport implements [http.RoundTripper] by using
// tokens from the CUE login information when available, falling
// back to using the standard [ociauth] transport implementation.
type cueLoginsTransport struct {
cfg *Config
getenv func(string) string
// initOnce guards initErr, logins, and transport.
initOnce sync.Once
initErr error
logins *cueconfig.Logins
// transport holds the underlying transport. This wraps
// t.cfg.Transport.
transport http.RoundTripper
// mu guards the fields below.
mu sync.Mutex
// cachedTransports holds a transport per host.
// This is needed because the oauth2 API requires a
// different client for each host. Each of these transports
// wraps the transport above.
cachedTransports map[string]http.RoundTripper
}
func (t *cueLoginsTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Return an error lazily on the first request because if the
// user isn't doing anything that requires a registry, we
// shouldn't complain about reading a bad configuration file.
if err := t.init(); err != nil {
return nil, err
}
if t.logins == nil {
return t.transport.RoundTrip(req)
}
// TODO: note that a CUE registry may include a path prefix,
// so using solely the host will not work with such a path.
// Can we do better here, perhaps keeping the path prefix up to "/v2/"?
host := req.URL.Host
login, ok := t.logins.Registries[host]
if !ok {
return t.transport.RoundTrip(req)
}
t.mu.Lock()
transport := t.cachedTransports[host]
if transport == nil {
tok := cueconfig.TokenFromLogin(login)
oauthCfg := cueconfig.RegistryOAuthConfig(Host{
Name: host,
Insecure: req.URL.Scheme == "http",
})
// TODO: When this client refreshes an access token,
// we should store the refreshed token on disk.
// Make the oauth client use the transport that was set up
// in init.
ctx := context.WithValue(req.Context(), oauth2.HTTPClient, &http.Client{
Transport: t.transport,
})
transport = oauthCfg.Client(ctx, tok).Transport
t.cachedTransports[host] = transport
}
// Unlock immediately so we don't hold the lock for the entire
// request, which would preclude any concurrency when
// making HTTP requests.
t.mu.Unlock()
return transport.RoundTrip(req)
}
func (t *cueLoginsTransport) init() error {
t.initOnce.Do(func() {
t.initErr = t._init()
})
return t.initErr
}
func (t *cueLoginsTransport) _init() error {
// If a registry was authenticated via `cue login`, use that.
// If not, fall back to authentication via Docker's config.json.
// Note that the order below is backwards, since we layer interfaces.
config, err := ociauth.LoadWithEnv(nil, t.cfg.Env)
if err != nil {
return fmt.Errorf("cannot load OCI auth configuration: %v", err)
}
t.transport = ociauth.NewStdTransport(ociauth.StdTransportParams{
Config: config,
Transport: t.cfg.Transport,
})
// If we can't locate a logins.json file at all, then we'll
// We only refuse to continue if we find an invalid logins.json file.
loginsPath, err := cueconfig.LoginConfigPath(t.getenv)
if err != nil {
return nil
}
logins, err := cueconfig.ReadLogins(loginsPath)
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("cannot load CUE registry logins: %v", err)
}
t.logins = logins
t.cachedTransports = make(map[string]http.RoundTripper)
return nil
}
// NewRegistry returns an implementation of the Registry
// interface suitable for passing to [load.Instances].
// It uses the standard CUE cache directory.
func NewRegistry(cfg *Config) (Registry, error) {
cfg = newRef(cfg)
resolver, err := NewResolver(cfg)
if err != nil {
return nil, err
}
cacheDir, err := cueconfig.CacheDir(getenvFunc(cfg.Env))
if err != nil {
return nil, err
}
return modcache.New(modregistry.NewClientWithResolver(resolver), cacheDir)
}
func getenvFunc(env []string) func(string) string {
if env == nil {
return os.Getenv
}
return func(key string) string {
for i := len(env) - 1; i >= 0; i-- {
if e := env[i]; len(e) >= len(key)+1 && e[len(key)] == '=' && e[:len(key)] == key {
return e[len(key)+1:]
}
}
return ""
}
}
func newRef[T any](x *T) *T {
var x1 T
if x != nil {
x1 = *x
}
return &x1
}