Skip to content
quarry Artifact [59f6d99f22]
Login

Artifact [59f6d99f22]

Artifact 59f6d99f22135932e4ee7c7d5c60d0d04dcf4fb575d3285c0d6e68c5d256e58c:


package outbound

import (
	"go/ast"
	"go/parser"
	"go/token"
	"io/fs"
	"path/filepath"
	"strings"
	"testing"
)

// The packages that talk to a destination a user chose build their HTTP
// clients with this package, never with net/http's own constructors: an
// unguarded client there is a read of the forge's internal network. This
// walks the sources and fails on a new one, the way the mail test fails
// on a second Mail.Send.
//
// Each exception is a client that only ever talks to an address the
// operator configured, and says so.
func TestUserFacingPackagesBuildNoUnguardedClient(t *testing.T) {
	roots := []string{"../api", "../webhook", "../s3", "../chat", "../xfer", "../imgproxy", "../web", "../../cmd/quarry"}
	// Keyed by file, enclosing function ("var" outside any), and what is built.
	allowed := map[string]string{
		"xfer.go:var:http.Client":                      "the proxy to the forge's own backend",
		"githubabout.go:copyGitHubAbout:DefaultClient": "GitHub's API root, fixed by the forge",
		"repocmd.go:call:http.Client":                  "the CLI talking to the forge URL its operator typed",
	}
	banned := map[string]bool{"DefaultClient": true, "DefaultTransport": true, "Get": true, "Post": true, "Head": true, "PostForm": true}
	fset := token.NewFileSet()
	var found []string
	for _, root := range roots {
		filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error {
			if err != nil || e.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
				return nil
			}
			f, perr := parser.ParseFile(fset, path, nil, 0)
			if perr != nil {
				t.Fatal(perr)
			}
			// Whatever net/http is imported as in this file.
			names := map[string]bool{}
			for _, im := range f.Imports {
				if im.Path.Value != `"net/http"` {
					continue
				}
				if im.Name == nil {
					names["http"] = true
				} else if im.Name.Name != "_" {
					names[im.Name.Name] = true
				}
			}
			isHTTP := func(x ast.Expr) bool {
				id, ok := x.(*ast.Ident)
				return ok && names[id.Name]
			}
			clientType := func(x ast.Expr) string {
				if sel, ok := x.(*ast.SelectorExpr); ok && isHTTP(sel.X) && (sel.Sel.Name == "Client" || sel.Sel.Name == "Transport") {
					return "http." + sel.Sel.Name
				}
				return ""
			}
			base := filepath.Base(path)
			for _, decl := range f.Decls {
				fn := "var"
				if fd, ok := decl.(*ast.FuncDecl); ok {
					fn = fd.Name.Name
				}
				ast.Inspect(decl, func(n ast.Node) bool {
					switch x := n.(type) {
					case *ast.CompositeLit:
						if c := clientType(x.Type); c != "" {
							found = append(found, base+":"+fn+":"+c)
						}
					case *ast.CallExpr:
						if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "new" && len(x.Args) == 1 {
							if c := clientType(x.Args[0]); c != "" {
								found = append(found, base+":"+fn+":"+c)
							}
						}
					case *ast.SelectorExpr:
						if isHTTP(x.X) && banned[x.Sel.Name] {
							found = append(found, base+":"+fn+":"+x.Sel.Name)
						}
					}
					return true
				})
			}
			return nil
		})
	}
	used := map[string]bool{}
	for _, f := range found {
		if _, ok := allowed[f]; !ok {
			t.Errorf("FAIL: %s builds an unguarded HTTP client; use outbound.NewClient or outbound.Client", f)
		}
		used[f] = true
	}
	// An exception nobody uses any more is a hole in the list.
	for k := range allowed {
		if !used[k] {
			t.Errorf("FAIL: the exception %s no longer matches anything; remove it", k)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}