diff --git a/gitclient/gitclient.go b/gitclient/gitclient.go index 7fcd6930d..d3577f8ff 100644 --- a/gitclient/gitclient.go +++ b/gitclient/gitclient.go @@ -10,6 +10,7 @@ import ( "io" "maps" "net/http" + "path" "slices" "strings" "sync" @@ -18,6 +19,7 @@ import ( var ( ErrRefNotFound = errors.New("branch or tag not found") ErrPathNotFound = errors.New("path not found at the commit") + ErrNotDir = fmt.Errorf("%w: not a directory", ErrPathNotFound) ErrTooLarge = errors.New("pack exceeds the read limit") ErrUnsupported = errors.New("server lacks a required v2 capability") ) @@ -41,7 +43,6 @@ func New(httpClient *http.Client, repoURL string, maxBytes int64) *Client { return &Client{http: httpClient, url: strings.TrimSuffix(repoURL, "/"), maxBytes: maxBytes} } -// from GET info/refs?service=git-upload-pack with Git-Protocol: version=2 type Caps struct { ObjectFormat string // "sha1" or "sha256" LsRefs bool @@ -223,8 +224,7 @@ func (c *Client) Fetch(ctx context.Context, opts FetchOpts) (Objects, error) { return objs, nil } -// commit oid for refs/heads/x, refs/tags/x or a bare name (branches before -// tags, like git), tags peeled; ErrRefNotFound when ls-refs lists none of them +// branches before tags, like git; tags peeled func (c *Client) Resolve(ctx context.Context, ref string) (Oid, error) { if ref == "" || strings.ContainsAny(ref, "\x00\n ") { return "", ErrRefNotFound @@ -258,85 +258,123 @@ type File struct { Data []byte // nil for subtrees and submodules } -// entries of dir at commit with blob contents. knot2 walks its whole repo to -// check each want that isn't a commit, so these are kept to a minimum: the -// commit comes with its root tree (deepen 1, tree:1, which every server counts -// from the commit alike), middle trees come alone (tree:0), and the last tree -// asks for tree:1, which knot2 answers with its blobs too. filter depth for a -// wanted tree differs between servers, so blobs still missing are wanted by -// oid. ErrPathNotFound when a component is missing or isn't a tree +// one level of dir, blobs filled in func (c *Client) ReadDir(ctx context.Context, commit Oid, dir string) ([]File, error) { - caps, err := c.Caps(ctx) + caps, objs, oid, err := c.walk(ctx, commit, dir) if err != nil { return nil, err } - objs, err := c.Fetch(ctx, FetchOpts{Wants: []Oid{commit}, Deepen: 1, Filter: "tree:1"}) + entries, err := c.tree(ctx, caps, objs, oid, "tree:1") if err != nil { return nil, err } - obj, ok := objs[commit] - if !ok || obj.Kind != KindCommit { - return nil, fmt.Errorf("fetch of commit %s didn't return it", commit) + files := make([]File, 0, len(entries)) + for _, e := range entries { + files = append(files, File{Name: e.Name, Mode: e.Mode, Oid: e.Oid}) } - tree, err := commitTree(obj.Data) + if err := c.fillBlobs(ctx, objs, files); err != nil { + return nil, err + } + return files, nil +} + +// everything under dir, named relative to it; the dir tree is wanted unfiltered +// so one pack brings it all +func (c *Client) ReadTree(ctx context.Context, commit Oid, dir string) ([]File, error) { + caps, objs, oid, err := c.walk(ctx, commit, dir) if err != nil { return nil, err } - var names []string - for _, name := range strings.Split(dir, "/") { - if name != "" { - names = append(names, name) + var files []File + queue := []File{{Oid: oid}} + for len(queue) > 0 { + t := queue[0] + queue = queue[1:] + entries, err := c.tree(ctx, caps, objs, t.Oid, "") + if err != nil { + return nil, err + } + for _, e := range entries { + f := File{Name: path.Join(t.Name, e.Name), Mode: e.Mode, Oid: e.Oid} + if isTreeMode(e.Mode) { + queue = append(queue, f) + } + files = append(files, f) } } - entries, err := c.tree(ctx, caps, objs, tree, "tree:0") - if err != nil { + if err := c.fillBlobs(ctx, objs, files); err != nil { return nil, err } - for n, name := range names { - i := slices.IndexFunc(entries, func(e treeEntry) bool { return e.Name == name }) - if i < 0 || strings.TrimLeft(entries[i].Mode, "0") != "40000" { - return nil, fmt.Errorf("%s: %w", dir, ErrPathNotFound) + return files, nil +} + +// middle trees come alone (tree:0) so sibling blobs stay on the server; servers +// differ on filter depth for a wanted tree, hence fillBlobs +func (c *Client) walk(ctx context.Context, commit Oid, dir string) (Caps, Objects, Oid, error) { + caps, err := c.Caps(ctx) + if err != nil { + return Caps{}, nil, "", err + } + objs, err := c.Fetch(ctx, FetchOpts{Wants: []Oid{commit}, Deepen: 1, Filter: "tree:1"}) + if err != nil { + return Caps{}, nil, "", err + } + obj, ok := objs[commit] + if !ok || obj.Kind != KindCommit { + return Caps{}, nil, "", fmt.Errorf("fetch of commit %s didn't return it", commit) + } + tree, err := commitTree(obj.Data) + if err != nil { + return Caps{}, nil, "", err + } + for _, name := range strings.Split(dir, "/") { + if name == "" { + continue } - filter := "tree:0" - if n == len(names)-1 { - filter = "tree:1" + entries, err := c.tree(ctx, caps, objs, tree, "tree:0") + if err != nil { + return Caps{}, nil, "", err } - if entries, err = c.tree(ctx, caps, objs, entries[i].Oid, filter); err != nil { - return nil, err + i := slices.IndexFunc(entries, func(e treeEntry) bool { return e.Name == name }) + if i < 0 { + return Caps{}, nil, "", fmt.Errorf("%s: %w", dir, ErrPathNotFound) } + if !isTreeMode(entries[i].Mode) { + return Caps{}, nil, "", fmt.Errorf("%s: %w", dir, ErrNotDir) + } + tree = entries[i].Oid } + return caps, objs, tree, nil +} +func (c *Client) fillBlobs(ctx context.Context, objs Objects, files []File) error { var missing []Oid - for _, e := range entries { - if _, ok := objs[e.Oid]; isBlobMode(e.Mode) && !ok && !slices.Contains(missing, e.Oid) { - missing = append(missing, e.Oid) + for _, f := range files { + if _, ok := objs[f.Oid]; isBlobMode(f.Mode) && !ok && !slices.Contains(missing, f.Oid) { + missing = append(missing, f.Oid) } } if len(missing) > 0 { // wanted objects pass any filter; it keeps the server on its selective path more, err := c.Fetch(ctx, FetchOpts{Wants: missing, Filter: "tree:0"}) if err != nil { - return nil, err + return err } maps.Copy(objs, more) } - files := make([]File, 0, len(entries)) - for _, e := range entries { - f := File{Name: e.Name, Mode: e.Mode, Oid: e.Oid} - if isBlobMode(e.Mode) { - obj, ok := objs[e.Oid] - if !ok || obj.Kind != KindBlob { - return nil, fmt.Errorf("fetch of blob %s didn't return it", e.Oid) - } - f.Data = obj.Data + for i, f := range files { + if !isBlobMode(f.Mode) { + continue + } + obj, ok := objs[f.Oid] + if !ok || obj.Kind != KindBlob { + return fmt.Errorf("fetch of blob %s didn't return it", f.Oid) } - files = append(files, f) + files[i].Data = obj.Data } - return files, nil + return nil } -// entries of tree oid, fetched with filter unless an earlier fetch brought it; -// whatever else the fetch returns lands in have func (c *Client) tree(ctx context.Context, caps Caps, have Objects, oid Oid, filter string) ([]treeEntry, error) { if _, ok := have[oid]; !ok { objs, err := c.Fetch(ctx, FetchOpts{Wants: []Oid{oid}, Filter: filter}) @@ -352,13 +390,15 @@ func (c *Client) tree(ctx context.Context, caps Caps, have Objects, oid Oid, fil return parseTree(obj.Data, caps.ObjectFormat) } -// anything but subtrees and submodules func isBlobMode(mode string) bool { mode = strings.TrimLeft(mode, "0") return mode != "40000" && mode != "160000" } -// one POST git-upload-pack with a v2 command body +func isTreeMode(mode string) bool { + return strings.TrimLeft(mode, "0") == "40000" +} + func (c *Client) command(ctx context.Context, caps Caps, command string, args []string) (*http.Response, error) { var body bytes.Buffer writePkt(&body, "command="+command+"\n") diff --git a/gitclient/gitclient_test.go b/gitclient/gitclient_test.go index 39eadef41..da36f909c 100644 --- a/gitclient/gitclient_test.go +++ b/gitclient/gitclient_test.go @@ -115,6 +115,30 @@ func TestStockGit(t *testing.T) { } } + if _, err := c.ReadDir(ctx, Oid(second), ".tangled/workflows/a.yml"); !errors.Is(err, ErrNotDir) { + t.Errorf("ReadDir(a.yml) = %v", err) + } + + files, err = c.ReadTree(ctx, Oid(second), "/.tangled") + if err != nil { + t.Fatal(err) + } + got = nil + for _, f := range files { + got = append(got, f.Mode+" "+f.Name+" "+string(f.Data)) + } + want = []string{"40000 workflows ", "100644 workflows/a.yml when: push\n", "100755 workflows/b.yml when: pr\n", + "120000 workflows/link a.yml", "40000 workflows/sub ", "100644 workflows/sub/c.yml nested\n"} + if strings.Join(got, "|") != strings.Join(want, "|") { + t.Errorf("ReadTree = %q", got) + } + if _, err := c.ReadTree(ctx, Oid(second), "nope"); !errors.Is(err, ErrPathNotFound) || errors.Is(err, ErrNotDir) { + t.Errorf("ReadTree(nope) = %v", err) + } + if _, err := c.ReadTree(ctx, Oid(second), "README/x"); !errors.Is(err, ErrNotDir) { + t.Errorf("ReadTree(README/x) = %v", err) + } + small := New(srv.Client(), srv.URL+"/repo", 64) if _, err := small.ReadDir(ctx, Oid(second), ".tangled/workflows"); !errors.Is(err, ErrTooLarge) { t.Errorf("small ReadDir = %v", err) diff --git a/sitesd/sites/sites.go b/sitesd/sites/sites.go index f91d56373..e3b51cfa5 100644 --- a/sitesd/sites/sites.go +++ b/sitesd/sites/sites.go @@ -1,22 +1,14 @@ package sites import ( - "archive/tar" - "bytes" - "compress/gzip" "context" "errors" "fmt" - "io" - "io/fs" - "os" "path" - "path/filepath" "strings" - lexutil "github.com/bluesky-social/indigo/lex/util" - indigoxrpc "github.com/bluesky-social/indigo/xrpc" "tangled.org/core/appview/models" + "tangled.org/core/gitclient" "tangled.org/core/sitesd/cloudflare" "tangled.org/core/sitesd/config" ) @@ -25,6 +17,9 @@ func prefix(repoDid, rkey string) string { return repoDid + "/" + rkey + "/" } +// cap on one fetch's pack, which is normally the whole deploy directory +const maxPackBytes = 256 << 20 + func Deploy( ctx context.Context, cf *cloudflare.Client, @@ -33,22 +28,16 @@ func Deploy( branch string, deployDir string, ) error { - tmpDir, err := os.MkdirTemp("", "tangled-sites-*") - if err != nil { - return fmt.Errorf("creating temp dir: %w", err) - } - defer os.RemoveAll(tmpDir) - - if err := extractArchive(ctx, f, branch, tmpDir); err != nil { - return fmt.Errorf("extracting archive: %w", err) + // plain http to a dev knot only reaches caddy's redirect, so always ask over https + git := gitclient.New(nil, "https://"+f.Knot+"/"+f.RepoDid, maxPackBytes) + commit, err := git.Resolve(ctx, branch) + if errors.Is(err, gitclient.ErrRefNotFound) { + return fmt.Errorf("branch %q does not exist", branch) } - - deployRoot := filepath.Join(tmpDir, filepath.FromSlash(deployDir)) - rel, err := filepath.Rel(tmpDir, deployRoot) - if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return fmt.Errorf("deploy directory %q escapes the archive", deployDir) + if err != nil { + return fmt.Errorf("resolving branch %q: %w", branch, err) } - files, err := collectFiles(deployRoot, deployDir) + files, err := readDeployDir(ctx, git, commit, deployDir) if err != nil { return err } @@ -60,138 +49,33 @@ func Deploy( return nil } -// error text goes to the user's deploy history, so it names deployDir and never the temp deployRoot -func collectFiles(deployRoot, deployDir string) (map[string][]byte, error) { - root, err := os.Stat(deployRoot) - if errors.Is(err, fs.ErrNotExist) { - return nil, fmt.Errorf("deploy directory %q does not exist", deployDir) +// regular files under deployDir by relative path; symlinks and submodules are +// never uploaded. error text goes to the user's deploy history +func readDeployDir(ctx context.Context, git *gitclient.Client, commit gitclient.Oid, deployDir string) (map[string][]byte, error) { + dir := path.Clean("./" + deployDir) + if dir == ".." || strings.HasPrefix(dir, "../") { + return nil, fmt.Errorf("deploy directory %q escapes the repo", deployDir) } - if err != nil { - return nil, fmt.Errorf("opening deploy directory %q: %w", deployDir, withoutPath(err)) + if dir == "." { + dir = "" } - if !root.IsDir() { + entries, err := git.ReadTree(ctx, commit, dir) + switch { + case errors.Is(err, gitclient.ErrNotDir): return nil, fmt.Errorf("deploy directory %q is not a directory", deployDir) + case errors.Is(err, gitclient.ErrPathNotFound): + return nil, fmt.Errorf("deploy directory %q does not exist", deployDir) + case err != nil: + return nil, fmt.Errorf("reading deploy directory %q: %w", deployDir, err) } - files := make(map[string][]byte) - err = filepath.WalkDir(deployRoot, func(p string, d fs.DirEntry, err error) error { - if err != nil { - return err + for _, e := range entries { + if strings.HasPrefix(e.Mode, "100") { + files[e.Name] = e.Data } - if d.IsDir() { - return nil - } - rel, err := filepath.Rel(deployRoot, p) - if err != nil { - return err - } - rel = filepath.ToSlash(rel) - if !d.Type().IsRegular() { - return fmt.Errorf("deploy entry %q is not a regular file", path.Join(deployDir, rel)) - } - content, err := os.ReadFile(p) - if err != nil { - return err - } - files[rel] = content - return nil - }) - if err != nil { - return nil, withoutPath(err) } if len(files) == 0 { return nil, fmt.Errorf("deploy directory %q contains no files", deployDir) } return files, nil } - -func withoutPath(err error) error { - var pathErr *fs.PathError - if errors.As(err, &pathErr) { - return fmt.Errorf("%s: %w", pathErr.Op, pathErr.Err) - } - return err -} - -const archiveNSID = "org.tangled.git.getArchive" - -// the archive prefix is stripped again on extract, so its name doesn't matter -const archivePrefix = "site/" - -func extractArchive(ctx context.Context, f *models.Repo, branch, destDir string) error { - // plain http to a dev knot only reaches caddy's redirect, so always ask over https - xrpcc := &indigoxrpc.Client{Host: "https://" + f.Knot} - params := map[string]any{ - "repo": f.RepoDid, - "ref": branch, - "format": "tar.gz", - "prefix": archivePrefix, - } - var data bytes.Buffer - if err := xrpcc.LexDo(ctx, lexutil.Query, "", archiveNSID, params, nil, &data); err != nil { - return fmt.Errorf("fetching archive: %w", err) - } - - return extractTarGz(&data, destDir) -} - -// strip git archive prefix, rejecting paths outside the destination -func extractTarGz(r io.Reader, destDir string) error { - gz, err := gzip.NewReader(r) - if err != nil { - return fmt.Errorf("opening gzip stream: %w", err) - } - defer gz.Close() - - root := filepath.Clean(destDir) + string(os.PathSeparator) - tr := tar.NewReader(gz) - for { - hdr, err := tr.Next() - if err == io.EOF { - return nil - } - if err != nil { - return fmt.Errorf("reading tar: %w", err) - } - - name := hdr.Name - i := strings.Index(name, "/") - if i < 0 { - continue - } - name = name[i+1:] - if name == "" { - continue - } - - target := filepath.Join(destDir, filepath.FromSlash(name)) - if !strings.HasPrefix(target, root) { - continue - } - - switch hdr.Typeflag { - case tar.TypeDir: - if err := os.MkdirAll(target, 0o755); err != nil { - return err - } - case tar.TypeReg: - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - return err - } - out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, hdr.FileInfo().Mode()) - if err != nil { - return err - } - if _, err := io.Copy(out, tr); err != nil { - out.Close() - return err - } - out.Close() - case tar.TypeSymlink: - // never read archive symlink targets into r2 - continue - default: - return fmt.Errorf("unsupported archive entry: name %q type %d", hdr.Name, hdr.Typeflag) - } - } -} diff --git a/sitesd/sites/sites_test.go b/sitesd/sites/sites_test.go index 851dfd716..eab176fb9 100644 --- a/sitesd/sites/sites_test.go +++ b/sitesd/sites/sites_test.go @@ -1,280 +1,136 @@ package sites import ( - "archive/tar" - "bytes" - "compress/gzip" "context" - "io/fs" + "net/http/cgi" + "net/http/httptest" "os" "os/exec" + "path" "path/filepath" + "slices" "strings" "testing" - "tangled.org/core/gitutil" + "tangled.org/core/gitclient" ) -type entry struct { - name string - typ byte - linkname string - body string -} - -func dir(name string) entry { return entry{name: name, typ: tar.TypeDir} } -func reg(name, body string) entry { return entry{name: name, typ: tar.TypeReg, body: body} } -func link(name, target string) entry { - return entry{name: name, typ: tar.TypeSymlink, linkname: target} -} - -// tar reader surfaces the git archive pax global header -func fixtureArchive(t *testing.T, entries ...entry) []byte { - t.Helper() - var buf bytes.Buffer - gz := gzip.NewWriter(&buf) - tw := tar.NewWriter(gz) - - if err := tw.WriteHeader(&tar.Header{ - Name: "pax_global_header", - Typeflag: tar.TypeXGlobalHeader, - Format: tar.FormatPAX, - PAXRecords: map[string]string{"comment": "9d7184ed07b789e74726e1af20c3d4ab3410418e"}, - }); err != nil { - t.Fatalf("writing pax global header: %v", err) - } - for _, e := range entries { - hdr := &tar.Header{Name: e.name, Typeflag: e.typ, Mode: 0o644, Linkname: e.linkname, Size: int64(len(e.body))} - switch e.typ { - case tar.TypeDir: - hdr.Mode = 0o755 - case tar.TypeSymlink: - hdr.Mode = 0o777 - } - if err := tw.WriteHeader(hdr); err != nil { - t.Fatalf("writing header %q: %v", e.name, err) - } - if _, err := tw.Write([]byte(e.body)); err != nil { - t.Fatalf("writing body %q: %v", e.name, err) - } - } - if err := tw.Close(); err != nil { - t.Fatal(err) - } - if err := gz.Close(); err != nil { - t.Fatal(err) - } - return buf.Bytes() -} - -func requireFile(t *testing.T, path, want string) { +// a repo served by git http-backend, as the knot serves it over smart http +func fixtureRepo(t *testing.T) (*gitclient.Client, gitclient.Oid) { t.Helper() - got, err := os.ReadFile(path) + gitPath, err := exec.LookPath("git") if err != nil { - t.Errorf("reading %s: %v", path, err) - return - } - if string(got) != want { - t.Errorf("%s = %q, want %q", path, got, want) + t.Skip("no git binary") } -} - -func requireAbsent(t *testing.T, dest string, names ...string) { - t.Helper() - for _, name := range names { - path := filepath.Join(dest, filepath.FromSlash(name)) - if _, err := os.Lstat(path); !os.IsNotExist(err) { - t.Errorf("%s exists (lstat err = %v), want nothing extracted there", name, err) - } - } -} - -func requireOnlyDirsAndFiles(t *testing.T, dest string) { - t.Helper() - err := filepath.WalkDir(dest, func(p string, d fs.DirEntry, err error) error { + root := t.TempDir() + repo := filepath.Join(root, "repo") + env := append(os.Environ(), + "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", + "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t") + git := func(args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = repo + cmd.Env = env + out, err := cmd.Output() if err != nil { - return err - } - if !d.IsDir() && !d.Type().IsRegular() { - t.Errorf("%s is %v, want only dirs and regular files", p, d.Type()) + t.Fatalf("git %v: %v", args, err) } - return nil - }) - if err != nil { - t.Fatal(err) - } -} - -func TestExtractTarGzSkipsCommittedSymlinks(t *testing.T) { - dest := t.TempDir() - archive := fixtureArchive(t, - dir("repo-main/"), - dir("repo-main/docs/"), - reg("repo-main/docs/index.html", "