Debian Codegraph @

goproxytest/proxy.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 /*
6 Package goproxytest serves Go modules from a proxy server designed to run on
7 localhost during tests, both to make tests avoid requiring specific network
8 servers and also to make them significantly faster.
9
10 Each module archive is either a file named path_vers.txtar or path_vers.txt, or
11 a directory named path_vers, where slashes in path have been replaced with underscores.
12 The archive or directory may contain files ".info" and ".mod", to be served as
13 the info and mod files in the proxy protocol (see
14 https://research.swtch.com/vgo-module). If ".mod" is not present, the
15 content of the "go.mod" file is used. If ".info" is not present,
16 it is synthesized from the version with the Unix epoch as timestamp.
17
18 The remaining files are served as the content of the module zip file.
19 The path@vers prefix required of files in the zip file is added
20 automatically by the proxy: the files in the archive have names without
21 the prefix, like plain "go.mod", "x.go", and so on.
22
23 See ../cmd/txtar-addmod and ../cmd/txtar-c for tools generate txtar
24 files, although it's fine to write them by hand.
25 */
26 package goproxytest
27
28 import (
29 "archive/zip"
30 "bytes"
31 "cmp"
32 "encoding/json"
33 "fmt"
34 "io/fs"
35 "iter"
36 "log"
37 "net"
38 "net/http"
39 "os"
40 "path/filepath"
41 "strings"
42 "testing"
43
44 "golang.org/x/mod/module"
45 "golang.org/x/mod/semver"
46 "golang.org/x/tools/txtar"
47
48 "github.com/rogpeppe/go-internal/par"
49 )
50
51 type Server struct {
52 server *http.Server
53 URL string
54 dir string
55 logf func(string, ...any)
56 modList []module.Version
57 zipCache par.Cache
58 archiveCache par.Cache
59 }
60
61 // NewTestServer is a wrapper around [NewServer] for use in Go tests.
62 // Failure to start the server stops the test via [testing.TB.Fatalf],
63 // all server logs go through [testing.TB.Logf],
64 // and the server is closed when the test finishes via [testing.TB.Cleanup].
65 func NewTestServer(tb testing.TB, dir, addr string) *Server {
66 srv, err := newServer(dir, addr, tb.Logf)
67 if err != nil {
68 tb.Fatalf("cannot start Go proxy: %v", err)
69 }
70 tb.Cleanup(srv.Close)
71 return srv
72 }
73
74 // NewServer starts the Go module proxy listening on the given
75 // network address. It serves modules taken from the given directory
76 // name. If addr is empty, it will listen on an arbitrary
77 // localhost port. If dir is empty, "testmod" will be used.
78 //
79 // The returned Server should be closed after use.
80 func NewServer(dir, addr string) (*Server, error) {
81 return newServer(dir, addr, log.Printf)
82 }
83
84 func newServer(dir, addr string, logf func(string, ...any)) (*Server, error) {
85 addr = cmp.Or(addr, "localhost:0")
86 dir = cmp.Or(dir, "testmod")
87 srv := Server{dir: dir, logf: logf}
88 if err := srv.readModList(); err != nil {
89 return nil, fmt.Errorf("cannot read modules: %v", err)
90 }
91 l, err := net.Listen("tcp", addr)
92 if err != nil {
93 return nil, fmt.Errorf("cannot listen on %q: %v", addr, err)
94 }
95 srv.server = &http.Server{
96 Handler: http.HandlerFunc(srv.handler),
97 }
98 addr = l.Addr().String()
99 srv.URL = "http://" + addr + "/mod"
100 go func() {
101 if err := srv.server.Serve(l); err != nil && err != http.ErrServerClosed {
102 srv.logf("go proxy_test: http.Serve: %v", err)
103 }
104 }()
105 return &srv, nil
106 }
107
108 // Close shuts down the proxy.
109 func (srv *Server) Close() {
110 srv.server.Close()
111 }
112
113 func (srv *Server) readModList() error {
114 entries, err := os.ReadDir(srv.dir)
115 if err != nil {
116 return err
117 }
118 for _, entry := range entries {
119 name := entry.Name()
120 switch {
121 case strings.HasSuffix(name, ".txt"):
122 name = strings.TrimSuffix(name, ".txt")
123 case strings.HasSuffix(name, ".txtar"):
124 name = strings.TrimSuffix(name, ".txtar")
125 case entry.IsDir():
126 default:
127 continue
128 }
129 i := strings.LastIndex(name, "_v")
130 if i < 0 {
131 continue
132 }
133 encPath := strings.ReplaceAll(name[:i], "_", "/")
134 path, err := module.UnescapePath(encPath)
135 if err != nil {
136 return fmt.Errorf("cannot decode module path in %q: %v", name, err)
137 }
138 encVers := name[i+1:]
139 vers, err := module.UnescapeVersion(encVers)
140 if err != nil {
141 return fmt.Errorf("cannot decode module version in %q: %v", name, err)
142 }
143 srv.modList = append(srv.modList, module.Version{Path: path, Version: vers})
144 }
145 return nil
146 }
147
148 // handler serves the Go module proxy protocol.
149 // See the proxy section of https://research.swtch.com/vgo-module.
150 func (srv *Server) handler(w http.ResponseWriter, r *http.Request) {
151 if !strings.HasPrefix(r.URL.Path, "/mod/") {
152 http.NotFound(w, r)
153 return
154 }
155 path := strings.TrimPrefix(r.URL.Path, "/mod/")
156 if enc, ok := strings.CutSuffix(path, "/@latest"); ok {
157 modPath, err := module.UnescapePath(enc)
158 if err != nil {
159 srv.logf("go proxy_test: %v\n", err)
160 http.NotFound(w, r)
161 return
162 }
163 best := latestVersion(func(yield func(string) bool) {
164 for _, m := range srv.modList {
165 if m.Path != modPath {
166 continue
167 }
168 if err := module.Check(m.Path, m.Version); err != nil {
169 continue
170 }
171 if !yield(m.Version) {
172 return
173 }
174 }
175 })
176 if best == "" {
177 http.NotFound(w, r)
178 return
179 }
180 a := srv.readArchive(modPath, best)
181 if a == nil {
182 http.NotFound(w, r)
183 return
184 }
185 for _, f := range a.Files {
186 if f.Name == ".info" {
187 w.Write(f.Data)
188 return
189 }
190 }
191 http.NotFound(w, r)
192 return
193 }
194 i := strings.Index(path, "/@v/")
195 if i < 0 {
196 http.NotFound(w, r)
197 return
198 }
199 enc, file := path[:i], path[i+len("/@v/"):]
200 path, err := module.UnescapePath(enc)
201 if err != nil {
202 srv.logf("go proxy_test: %v\n", err)
203 http.NotFound(w, r)
204 return
205 }
206 if file == "list" {
207 n := 0
208 for _, m := range srv.modList {
209 if m.Path == path && !isPseudoVersion(m.Version) {
210 if err := module.Check(m.Path, m.Version); err == nil {
211 fmt.Fprintf(w, "%s\n", m.Version)
212 n++
213 }
214 }
215 }
216 if n == 0 {
217 http.NotFound(w, r)
218 }
219 return
220 }
221
222 i = strings.LastIndex(file, ".")
223 if i < 0 {
224 http.NotFound(w, r)
225 return
226 }
227 encVers, ext := file[:i], file[i+1:]
228 vers, err := module.UnescapeVersion(encVers)
229 if err != nil {
230 srv.logf("go proxy_test: %v\n", err)
231 http.NotFound(w, r)
232 return
233 }
234
235 if allHex(vers) {
236 var best string
237 // Convert commit hash (only) to known version.
238 // Use latest version in semver priority, to match similar logic
239 // in the repo-based module server (see modfetch.(*codeRepo).convert).
240 for _, m := range srv.modList {
241 if m.Path == path && semver.Compare(best, m.Version) < 0 {
242 var hash string
243 if isPseudoVersion(m.Version) {
244 hash = m.Version[strings.LastIndex(m.Version, "-")+1:]
245 } else {
246 hash = srv.findHash(m)
247 }
248 if strings.HasPrefix(hash, vers) || strings.HasPrefix(vers, hash) {
249 best = m.Version
250 }
251 }
252 }
253 if best != "" {
254 vers = best
255 }
256 }
257
258 a := srv.readArchive(path, vers)
259 if a == nil {
260 // As of https://go-review.googlesource.com/c/go/+/189517, cmd/go
261 // resolves all paths. i.e. for github.com/hello/world, cmd/go attempts
262 // to resolve github.com, github.com/hello and github.com/hello/world.
263 // cmd/go expects a 404/410 response if there is nothing there. Hence we
264 // cannot return with a 500.
265 http.NotFound(w, r)
266 return
267 }
268
269 switch ext {
270 case "info", "mod":
271 want := "." + ext
272 for _, f := range a.Files {
273 if f.Name == want {
274 w.Write(f.Data)
275 return
276 }
277 }
278
279 case "zip":
280 type cached struct {
281 zip []byte
282 err error
283 }
284 c := srv.zipCache.Do(a, func() any {
285 var buf bytes.Buffer
286 z := zip.NewWriter(&buf)
287 for _, f := range a.Files {
288 if strings.HasPrefix(f.Name, ".") {
289 continue
290 }
291 zf, err := z.Create(path + "@" + vers + "/" + f.Name)
292 if err != nil {
293 return cached{nil, err}
294 }
295 if _, err := zf.Write(f.Data); err != nil {
296 return cached{nil, err}
297 }
298 }
299 if err := z.Close(); err != nil {
300 return cached{nil, err}
301 }
302 return cached{buf.Bytes(), nil}
303 }).(cached)
304
305 if c.err != nil {
306 srv.logf("go proxy_test: %v\n", c.err)
307 http.Error(w, c.err.Error(), 500)
308 return
309 }
310 w.Write(c.zip)
311 return
312
313 }
314 http.NotFound(w, r)
315 }
316
317 func (srv *Server) findHash(m module.Version) string {
318 a := srv.readArchive(m.Path, m.Version)
319 if a == nil {
320 return ""
321 }
322 var data []byte
323 for _, f := range a.Files {
324 if f.Name == ".info" {
325 data = f.Data
326 break
327 }
328 }
329 var info struct{ Short string }
330 json.Unmarshal(data, &info)
331 return info.Short
332 }
333
334 func (srv *Server) readArchive(path, vers string) *txtar.Archive {
335 enc, err := module.EscapePath(path)
336 if err != nil {
337 srv.logf("go proxy_test: %v\n", err)
338 return nil
339 }
340 encVers, err := module.EscapeVersion(vers)
341 if err != nil {
342 srv.logf("go proxy_test: %v\n", err)
343 return nil
344 }
345
346 prefix := strings.ReplaceAll(enc, "/", "_")
347 name := filepath.Join(srv.dir, prefix+"_"+encVers)
348 txtName := name + ".txt"
349 txtarName := name + ".txtar"
350 a := srv.archiveCache.Do(name, func() any {
351 a, err := txtar.ParseFile(txtarName)
352 if os.IsNotExist(err) {
353 // fall back to trying with the .txt extension
354 a, err = txtar.ParseFile(txtName)
355 }
356 if os.IsNotExist(err) {
357 // fall back to trying a directory
358 a = new(txtar.Archive)
359
360 err = filepath.WalkDir(name, func(fpath string, entry fs.DirEntry, err error) error {
361 if err != nil {
362 return err
363 }
364 if fpath == name && !entry.IsDir() {
365 return fmt.Errorf("expected a directory root")
366 }
367 if entry.IsDir() {
368 return nil
369 }
370 arpath := filepath.ToSlash(strings.TrimPrefix(fpath, name+string(os.PathSeparator)))
371 data, err := os.ReadFile(fpath)
372 if err != nil {
373 return err
374 }
375 a.Files = append(a.Files, txtar.File{
376 Name: arpath,
377 Data: data,
378 })
379 return nil
380 })
381 }
382 addDefaultFiles(a, path, vers)
383 if err != nil {
384 if !os.IsNotExist(err) {
385 srv.logf("go proxy_test: %v\n", err)
386 }
387 a = nil
388 }
389 return a
390 }).(*txtar.Archive)
391 return a
392 }
393
394 func addDefaultFiles(a *txtar.Archive, path, vers string) {
395 if _, ok := getFileData(a, ".info"); !ok {
396 info, _ := json.Marshal(struct {
397 Version string
398 Time string
399 }{vers, "1970-01-01T00:00:00Z"})
400 a.Files = append(a.Files, txtar.File{
401 Name: ".info",
402 Data: append(info, '\n'),
403 })
404 }
405 if _, ok := getFileData(a, ".mod"); !ok {
406 if data, ok := getFileData(a, "go.mod"); ok {
407 a.Files = append(a.Files, txtar.File{
408 Name: ".mod",
409 Data: data,
410 })
411 }
412 }
413 }
414
415 func getFileData(a *txtar.Archive, name string) ([]byte, bool) {
416 for _, f := range a.Files {
417 if f.Name == name {
418 return f.Data, true
419 }
420 }
421 return nil, false
422 }
423
424 // latestVersion returns the latest version from the given sequence,
425 // preferring release versions over pre-release versions.
426 // It returns the empty string if the sequence is empty.
427 func latestVersion(versions iter.Seq[string]) string {
428 var bestRelease, bestAny string
429 for v := range versions {
430 if semver.Prerelease(v) == "" && (bestRelease == "" || semver.Compare(v, bestRelease) > 0) {
431 bestRelease = v
432 }
433 if bestAny == "" || semver.Compare(v, bestAny) > 0 {
434 bestAny = v
435 }
436 }
437 if bestRelease != "" {
438 return bestRelease
439 }
440 return bestAny
441 }