Debian Codegraph @

sumdb/internal/sumweb/client.go

raw symbols SCIP
1 // Copyright 2019 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 package sumweb
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "path"
12 "strings"
13 "sync"
14 "sync/atomic"
15
16 "golang.org/x/exp/sumdb/internal/note"
17 "golang.org/x/exp/sumdb/internal/tlog"
18 )
19
20 // A Client provides the external operations
21 // (file caching, HTTP fetches, and so on)
22 // needed to implement the HTTP client Conn.
23 // The methods must be safe for concurrent use by multiple goroutines.
24 type Client interface {
25 // ReadRemote reads and returns the content served at the given path
26 // on the remote database server. The path begins with "/lookup" or "/tile/".
27 // It is the implementation's responsibility to turn that path into a full URL
28 // and make the HTTP request. ReadRemote should return an error for
29 // any non-200 HTTP response status.
30 ReadRemote(path string) ([]byte, error)
31
32 // ReadConfig reads and returns the content of the named configuration file.
33 // There are only a fixed set of configuration files.
34 //
35 // "key" returns a file containing the verifier key for the server.
36 //
37 // serverName + "/latest" returns a file containing the latest known
38 // signed tree from the server. It is read and written (using WriteConfig).
39 // To signal that the client wishes to start with an "empty" signed tree,
40 // ReadConfig can return a successful empty result (0 bytes of data).
41 ReadConfig(file string) ([]byte, error)
42
43 // WriteConfig updates the content of the named configuration file,
44 // changing it from the old []byte to the new []byte.
45 // If the old []byte does not match the stored configuration,
46 // WriteConfig must return ErrWriteConflict.
47 // Otherwise, WriteConfig should atomically replace old with new.
48 WriteConfig(file string, old, new []byte) error
49
50 // ReadCache reads and returns the content of the named cache file.
51 // Any returned error will be treated as equivalent to the file not existing.
52 // There can be arbitrarily many cache files, such as:
53 // serverName/lookup/pkg@version
54 // serverName/tile/8/1/x123/456
55 ReadCache(file string) ([]byte, error)
56
57 // WriteCache writes the named cache file.
58 WriteCache(file string, data []byte)
59
60 // Log prints the given log message (such as with log.Print)
61 Log(msg string)
62
63 // SecurityError prints the given security error log message.
64 // The Conn returns ErrSecurity from any operation that invokes SecurityError,
65 // but the return value is mainly for testing. In a real program,
66 // SecurityError should typically print the message and call log.Fatal or os.Exit.
67 SecurityError(msg string)
68 }
69
70 // ErrWriteConflict signals a write conflict during Client.WriteConfig.
71 var ErrWriteConflict = errors.New("write conflict")
72
73 // ErrSecurity is returned by Conn operations that invoke Client.SecurityError.
74 var ErrSecurity = errors.New("security error: misbehaving server")
75
76 // A Conn is a client connection to a go.sum database.
77 // All the methods are safe for simultaneous use by multiple goroutines.
78 type Conn struct {
79 client Client // client-provided external world
80
81 didLookup uint32
82
83 // one-time initialized data
84 initOnce sync.Once
85 initErr error // init error, if any
86 name string // name of accepted verifier
87 verifiers note.Verifiers // accepted verifiers (just one, but Verifiers for note.Open)
88 tileReader tileReader
89 tileHeight int
90 nosumdb string
91
92 record parCache // cache of record lookup, keyed by path@vers
93 tileCache parCache // cache of c.readTile, keyed by tile
94
95 latestMu sync.Mutex
96 latest tlog.Tree // latest known tree head
97 latestMsg []byte // encoded signed note for latest
98
99 tileSavedMu sync.Mutex
100 tileSaved map[tlog.Tile]bool // which tiles have been saved using c.client.WriteCache already
101 }
102
103 // NewConn returns a new Conn using the given Client.
104 func NewConn(client Client) *Conn {
105 return &Conn{
106 client: client,
107 }
108 }
109
110 // init initiailzes the conn (if not already initialized)
111 // and returns any initialization error.
112 func (c *Conn) init() error {
113 c.initOnce.Do(c.initWork)
114 return c.initErr
115 }
116
117 // initWork does the actual initialization work.
118 func (c *Conn) initWork() {
119 defer func() {
120 if c.initErr != nil {
121 c.initErr = fmt.Errorf("initializing sumweb.Conn: %v", c.initErr)
122 }
123 }()
124
125 c.tileReader.c = c
126 if c.tileHeight == 0 {
127 c.tileHeight = 8
128 }
129 c.tileSaved = make(map[tlog.Tile]bool)
130
131 vkey, err := c.client.ReadConfig("key")
132 if err != nil {
133 c.initErr = err
134 return
135 }
136 verifier, err := note.NewVerifier(strings.TrimSpace(string(vkey)))
137 if err != nil {
138 c.initErr = err
139 return
140 }
141 c.verifiers = note.VerifierList(verifier)
142 c.name = verifier.Name()
143
144 data, err := c.client.ReadConfig(c.name + "/latest")
145 if err != nil {
146 c.initErr = err
147 return
148 }
149 if err := c.mergeLatest(data); err != nil {
150 c.initErr = err
151 return
152 }
153 }
154
155 // SetTileHeight sets the tile height for the Conn.
156 // Any call to SetTileHeight must happen before the first call to Lookup.
157 // If SetTileHeight is not called, the Conn defaults to tile height 8.
158 func (c *Conn) SetTileHeight(height int) {
159 if atomic.LoadUint32(&c.didLookup) != 0 {
160 panic("SetTileHeight used after Lookup")
161 }
162 if c.tileHeight != 0 {
163 panic("multiple calls to SetTileHeight")
164 }
165 c.tileHeight = height
166 }
167
168 // SetGONOSUMDB sets the list of comma-separated GONOSUMDB patterns for the Conn.
169 // For any module path matching one of the patterns,
170 // Lookup will return ErrGONOSUMDB.
171 // Any call to SetGONOSUMDB must happen before the first call to Lookup.
172 func (c *Conn) SetGONOSUMDB(list string) {
173 if atomic.LoadUint32(&c.didLookup) != 0 {
174 panic("SetGONOSUMDB used after Lookup")
175 }
176 if c.nosumdb != "" {
177 panic("multiple calls to SetGONOSUMDB")
178 }
179 c.nosumdb = list
180 }
181
182 // ErrGONOSUMDB is returned by Lookup for paths that match
183 // a pattern listed in the GONOSUMDB list (set by SetGONOSUMDB,
184 // usually from the environment variable).
185 var ErrGONOSUMDB = errors.New("skipped (listed in GONOSUMDB)")
186
187 func (c *Conn) skip(target string) bool {
188 return globsMatchPath(c.nosumdb, target)
189 }
190
191 // globsMatchPath reports whether any path prefix of target
192 // matches one of the glob patterns (as defined by path.Match)
193 // in the comma-separated globs list.
194 // It ignores any empty or malformed patterns in the list.
195 func globsMatchPath(globs, target string) bool {
196 for globs != "" {
197 // Extract next non-empty glob in comma-separated list.
198 var glob string
199 if i := strings.Index(globs, ","); i >= 0 {
200 glob, globs = globs[:i], globs[i+1:]
201 } else {
202 glob, globs = globs, ""
203 }
204 if glob == "" {
205 continue
206 }
207
208 // A glob with N+1 path elements (N slashes) needs to be matched
209 // against the first N+1 path elements of target,
210 // which end just before the N+1'th slash.
211 n := strings.Count(glob, "/")
212 prefix := target
213 // Walk target, counting slashes, truncating at the N+1'th slash.
214 for i := 0; i < len(target); i++ {
215 if target[i] == '/' {
216 if n == 0 {
217 prefix = target[:i]
218 break
219 }
220 n--
221 }
222 }
223 if n > 0 {
224 // Not enough prefix elements.
225 continue
226 }
227 matched, _ := path.Match(glob, prefix)
228 if matched {
229 return true
230 }
231 }
232 return false
233 }
234
235 // Lookup returns the go.sum lines for the given module path and version.
236 // The version may end in a /go.mod suffix, in which case Lookup returns
237 // the go.sum lines for the module's go.mod-only hash.
238 func (c *Conn) Lookup(path, vers string) (lines []string, err error) {
239 atomic.StoreUint32(&c.didLookup, 1)
240
241 if c.skip(path) {
242 return nil, ErrGONOSUMDB
243 }
244
245 defer func() {
246 if err != nil {
247 err = fmt.Errorf("%s@%s: %v", path, vers, err)
248 }
249 }()
250
251 if err := c.init(); err != nil {
252 return nil, err
253 }
254
255 // Prepare encoded cache filename / URL.
256 epath, err := encodePath(path)
257 if err != nil {
258 return nil, err
259 }
260 evers, err := encodeVersion(strings.TrimSuffix(vers, "/go.mod"))
261 if err != nil {
262 return nil, err
263 }
264 file := c.name + "/lookup/" + epath + "@" + evers
265 remotePath := "/lookup/" + epath + "@" + evers
266
267 // Fetch the data.
268 // The lookupCache avoids redundant ReadCache/GetURL operations
269 // (especially since go.sum lines tend to come in pairs for a given
270 // path and version) and also avoids having multiple of the same
271 // request in flight at once.
272 type cached struct {
273 data []byte
274 err error
275 }
276 result := c.record.Do(file, func() interface{} {
277 // Try the on-disk cache, or else get from web.
278 writeCache := false
279 data, err := c.client.ReadCache(file)
280 if err != nil {
281 data, err = c.client.ReadRemote(remotePath)
282 if err != nil {
283 return cached{nil, err}
284 }
285 writeCache = true
286 }
287
288 // Validate the record before using it for anything.
289 id, text, treeMsg, err := tlog.ParseRecord(data)
290 if err != nil {
291 return cached{nil, err}
292 }
293 if err := c.mergeLatest(treeMsg); err != nil {
294 return cached{nil, err}
295 }
296 if err := c.checkRecord(id, text); err != nil {
297 return cached{nil, err}
298 }
299
300 // Now that we've validated the record,
301 // save it to the on-disk cache (unless that's where it came from).
302 if writeCache {
303 c.client.WriteCache(file, data)
304 }
305
306 return cached{data, nil}
307 }).(cached)
308 if result.err != nil {
309 return nil, result.err
310 }
311
312 // Extract the lines for the specific version we want
313 // (with or without /go.mod).
314 prefix := path + " " + vers + " "
315 var hashes []string
316 for _, line := range strings.Split(string(result.data), "\n") {
317 if strings.HasPrefix(line, prefix) {
318 hashes = append(hashes, line)
319 }
320 }
321 return hashes, nil
322 }
323
324 // mergeLatest merges the tree head in msg
325 // with the Conn's current latest tree head,
326 // ensuring the result is a consistent timeline.
327 // If the result is inconsistent, mergeLatest calls c.client.SecurityError
328 // with a detailed security error message and then
329 // (only if c.client.SecurityError does not exit the program) returns ErrSecurity.
330 // If the Conn's current latest tree head moves forward,
331 // mergeLatest updates the underlying configuration file as well,
332 // taking care to merge any independent updates to that configuration.
333 func (c *Conn) mergeLatest(msg []byte) error {
334 // Merge msg into our in-memory copy of the latest tree head.
335 when, err := c.mergeLatestMem(msg)
336 if err != nil {
337 return err
338 }
339 if when != msgFuture {
340 // msg matched our present or was in the past.
341 // No change to our present, so no update of config file.
342 return nil
343 }
344
345 // Flush our extended timeline back out to the configuration file.
346 // If the configuration file has been updated in the interim,
347 // we need to merge any updates made there as well.
348 // Note that writeConfig is an atomic compare-and-swap.
349 for {
350 msg, err := c.client.ReadConfig(c.name + "/latest")
351 if err != nil {
352 return err
353 }
354 when, err := c.mergeLatestMem(msg)
355 if err != nil {
356 return err
357 }
358 if when != msgPast {
359 // msg matched our present or was from the future,
360 // and now our in-memory copy matches.
361 return nil
362 }
363
364 // msg (== config) is in the past, so we need to update it.
365 c.latestMu.Lock()
366 latestMsg := c.latestMsg
367 c.latestMu.Unlock()
368 if err := c.client.WriteConfig(c.name+"/latest", msg, latestMsg); err != ErrWriteConflict {
369 // Success or a non-write-conflict error.
370 return err
371 }
372 }
373 }
374
375 const (
376 msgPast = 1 + iota
377 msgNow
378 msgFuture
379 )
380
381 // mergeLatestMem is like mergeLatest but is only concerned with
382 // updating the in-memory copy of the latest tree head (c.latest)
383 // not the configuration file.
384 // The when result explains when msg happened relative to our
385 // previous idea of c.latest:
386 // msgPast means msg was from before c.latest,
387 // msgNow means msg was exactly c.latest, and
388 // msgFuture means msg was from after c.latest, which has now been updated.
389 func (c *Conn) mergeLatestMem(msg []byte) (when int, err error) {
390 if len(msg) == 0 {
391 // Accept empty msg as the unsigned, empty timeline.
392 c.latestMu.Lock()
393 latest := c.latest
394 c.latestMu.Unlock()
395 if latest.N == 0 {
396 return msgNow, nil
397 }
398 return msgPast, nil
399 }
400
401 note, err := note.Open(msg, c.verifiers)
402 if err != nil {
403 return 0, fmt.Errorf("reading tree note: %v\nnote:\n%s", err, msg)
404 }
405 tree, err := tlog.ParseTree([]byte(note.Text))
406 if err != nil {
407 return 0, fmt.Errorf("reading tree: %v\ntree:\n%s", err, note.Text)
408 }
409
410 // Other lookups may be calling mergeLatest with other heads,
411 // so c.latest is changing underfoot. We don't want to hold the
412 // c.mu lock during tile fetches, so loop trying to update c.latest.
413 c.latestMu.Lock()
414 latest := c.latest
415 latestMsg := c.latestMsg
416 c.latestMu.Unlock()
417
418 for {
419 // If the tree head looks old, check that it is on our timeline.
420 if tree.N <= latest.N {
421 if err := c.checkTrees(tree, msg, latest, latestMsg); err != nil {
422 return 0, err
423 }
424 if tree.N < latest.N {
425 return msgPast, nil
426 }
427 return msgNow, nil
428 }
429
430 // The tree head looks new. Check that we are on its timeline and try to move our timeline forward.
431 if err := c.checkTrees(latest, latestMsg, tree, msg); err != nil {
432 return 0, err
433 }
434
435 // Install our msg if possible.
436 // Otherwise we will go around again.
437 c.latestMu.Lock()
438 installed := false
439 if c.latest == latest {
440 installed = true
441 c.latest = tree
442 c.latestMsg = msg
443 } else {
444 latest = c.latest
445 latestMsg = c.latestMsg
446 }
447 c.latestMu.Unlock()
448
449 if installed {
450 return msgFuture, nil
451 }
452 }
453 }
454
455 // checkTrees checks that older (from olderNote) is contained in newer (from newerNote).
456 // If an error occurs, such as malformed data or a network problem, checkTrees returns that error.
457 // If on the other hand checkTrees finds evidence of misbehavior, it prepares a detailed
458 // message and calls log.Fatal.
459 func (c *Conn) checkTrees(older tlog.Tree, olderNote []byte, newer tlog.Tree, newerNote []byte) error {
460 thr := tlog.TileHashReader(newer, &c.tileReader)
461 h, err := tlog.TreeHash(older.N, thr)
462 if err != nil {
463 if older.N == newer.N {
464 return fmt.Errorf("checking tree#%d: %v", older.N, err)
465 }
466 return fmt.Errorf("checking tree#%d against tree#%d: %v", older.N, newer.N, err)
467 }
468 if h == older.Hash {
469 return nil
470 }
471
472 // Detected a fork in the tree timeline.
473 // Start by reporting the inconsistent signed tree notes.
474 var buf bytes.Buffer
475 fmt.Fprintf(&buf, "SECURITY ERROR\n")
476 fmt.Fprintf(&buf, "go.sum database server misbehavior detected!\n\n")
477 indent := func(b []byte) []byte {
478 return bytes.Replace(b, []byte("\n"), []byte("\n\t"), -1)
479 }
480 fmt.Fprintf(&buf, "old database:\n\t%s\n", indent(olderNote))
481 fmt.Fprintf(&buf, "new database:\n\t%s\n", indent(newerNote))
482
483 // The notes alone are not enough to prove the inconsistency.
484 // We also need to show that the newer note's tree hash for older.N
485 // does not match older.Hash. The consumer of this report could
486 // of course consult the server to try to verify the inconsistency,
487 // but we are holding all the bits we need to prove it right now,
488 // so we might as well print them and make the report not depend
489 // on the continued availability of the misbehaving server.
490 // Preparing this data only reuses the tiled hashes needed for
491 // tlog.TreeHash(older.N, thr) above, so assuming thr is caching tiles,
492 // there are no new access to the server here, and these operations cannot fail.
493 fmt.Fprintf(&buf, "proof of misbehavior:\n\t%v", h)
494 if p, err := tlog.ProveTree(newer.N, older.N, thr); err != nil {
495 fmt.Fprintf(&buf, "\tinternal error: %v\n", err)
496 } else if err := tlog.CheckTree(p, newer.N, newer.Hash, older.N, h); err != nil {
497 fmt.Fprintf(&buf, "\tinternal error: generated inconsistent proof\n")
498 } else {
499 for _, h := range p {
500 fmt.Fprintf(&buf, "\n\t%v", h)
501 }
502 }
503 c.client.SecurityError(buf.String())
504 return ErrSecurity
505 }
506
507 // checkRecord checks that record #id's hash matches data.
508 func (c *Conn) checkRecord(id int64, data []byte) error {
509 c.latestMu.Lock()
510 latest := c.latest
511 c.latestMu.Unlock()
512
513 if id >= latest.N {
514 return fmt.Errorf("cannot validate record %d in tree of size %d", id, latest.N)
515 }
516 hashes, err := tlog.TileHashReader(latest, &c.tileReader).ReadHashes([]int64{tlog.StoredHashIndex(0, id)})
517 if err != nil {
518 return err
519 }
520 if hashes[0] == tlog.RecordHash(data) {
521 return nil
522 }
523 return fmt.Errorf("cannot authenticate record data in server response")
524 }
525
526 // tileReader is a *Conn wrapper that implements tlog.TileReader.
527 // The separate type avoids exposing the ReadTiles and SaveTiles
528 // methods on Conn itself.
529 type tileReader struct {
530 c *Conn
531 }
532
533 func (r *tileReader) Height() int {
534 return r.c.tileHeight
535 }
536
537 // ReadTiles reads and returns the requested tiles,
538 // either from the on-disk cache or the server.
539 func (r *tileReader) ReadTiles(tiles []tlog.Tile) ([][]byte, error) {
540 // Read all the tiles in parallel.
541 data := make([][]byte, len(tiles))
542 errs := make([]error, len(tiles))
543 var wg sync.WaitGroup
544 for i, tile := range tiles {
545 wg.Add(1)
546 go func(i int, tile tlog.Tile) {
547 defer wg.Done()
548 data[i], errs[i] = r.c.readTile(tile)
549 }(i, tile)
550 }
551 wg.Wait()
552
553 for _, err := range errs {
554 if err != nil {
555 return nil, err
556 }
557 }
558
559 return data, nil
560 }
561
562 // tileCacheKey returns the cache key for the tile.
563 func (c *Conn) tileCacheKey(tile tlog.Tile) string {
564 return c.name + "/" + tile.Path()
565 }
566
567 // tileRemotePath returns the remote path for the tile.
568 func (c *Conn) tileRemotePath(tile tlog.Tile) string {
569 return "/" + tile.Path()
570 }
571
572 // readTile reads a single tile, either from the on-disk cache or the server.
573 func (c *Conn) readTile(tile tlog.Tile) ([]byte, error) {
574 type cached struct {
575 data []byte
576 err error
577 }
578
579 result := c.tileCache.Do(tile, func() interface{} {
580 // Try the requested tile in on-disk cache.
581 data, err := c.client.ReadCache(c.tileCacheKey(tile))
582 if err == nil {
583 c.markTileSaved(tile)
584 return cached{data, nil}
585 }
586
587 // Try the full tile in on-disk cache (if requested tile not already full).
588 // We only save authenticated tiles to the on-disk cache,
589 // so the recreated prefix is equally authenticated.
590 full := tile
591 full.W = 1 << uint(tile.H)
592 if tile != full {
593 data, err := c.client.ReadCache(c.tileCacheKey(full))
594 if err == nil {
595 c.markTileSaved(tile) // don't save tile later; we already have full
596 return cached{data[:len(data)/full.W*tile.W], nil}
597 }
598 }
599
600 // Try requested tile from server.
601 data, err = c.client.ReadRemote(c.tileRemotePath(tile))
602 if err == nil {
603 return cached{data, nil}
604 }
605
606 // Try full tile on server.
607 // If the partial tile does not exist, it should be because
608 // the tile has been completed and only the complete one
609 // is available.
610 if tile != full {
611 data, err := c.client.ReadRemote(c.tileRemotePath(full))
612 if err == nil {
613 // Note: We could save the full tile in the on-disk cache here,
614 // but we don't know if it is valid yet, and we will only find out
615 // about the partial data, not the full data. So let SaveTiles
616 // save the partial tile, and we'll just refetch the full tile later
617 // once we can validate more (or all) of it.
618 return cached{data[:len(data)/full.W*tile.W], nil}
619 }
620 }
621
622 // Nothing worked.
623 // Return the error from the server fetch for the requested (not full) tile.
624 return cached{nil, err}
625 }).(cached)
626
627 return result.data, result.err
628 }
629
630 // markTileSaved records that tile is already present in the on-disk cache,
631 // so that a future SaveTiles for that tile can be ignored.
632 func (c *Conn) markTileSaved(tile tlog.Tile) {
633 c.tileSavedMu.Lock()
634 c.tileSaved[tile] = true
635 c.tileSavedMu.Unlock()
636 }
637
638 // SaveTiles saves the now validated tiles.
639 func (r *tileReader) SaveTiles(tiles []tlog.Tile, data [][]byte) {
640 c := r.c
641
642 // Determine which tiles need saving.
643 // (Tiles that came from the cache need not be saved back.)
644 save := make([]bool, len(tiles))
645 c.tileSavedMu.Lock()
646 for i, tile := range tiles {
647 if !c.tileSaved[tile] {
648 save[i] = true
649 c.tileSaved[tile] = true
650 }
651 }
652 c.tileSavedMu.Unlock()
653
654 for i, tile := range tiles {
655 if save[i] {
656 // If WriteCache fails here (out of disk space? i/o error?),
657 // c.tileSaved[tile] is still true and we will not try to write it again.
658 // Next time we run maybe we'll redownload it again and be
659 // more successful.
660 c.client.WriteCache(c.name+"/"+tile.Path(), data[i])
661 }
662 }
663 }