~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
435 lines · 12.5 KB Raw History
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/bluesky-social/indigo/atproto/repo"
	"github.com/bluesky-social/indigo/atproto/repo/mst"
	"github.com/ipfs/go-cid"
	car "github.com/ipld/go-car"
	"github.com/multiformats/go-multihash"
)

var repoClient = &http.Client{Timeout: 60 * time.Second}

// runRepo exports each repo named in a firehose summary and checks the CAR
// on its own terms (hashes, signature, canonical MST) and against the
// stream (rev, commit, data, records) and the read endpoints.
func runRepo(args []string) error {
	fs := flag.NewFlagSet("repo", flag.ExitOnError)
	pds := fs.String("pds", "http://127.0.0.1:2583", "PDS base URL")
	plc := fs.String("plc", "http://127.0.0.1:2582", "PLC directory")
	sumPath := fs.String("summary", "", "firehose summary to check the repos against")
	dids := fs.String("dids", "", "comma-separated DIDs to check instead of every active repo in the summary")
	fs.Parse(args)

	var sum summary
	if *sumPath != "" {
		b, err := readFile(*sumPath)
		if err != nil {
			return err
		}
		if err := json.Unmarshal(b, &sum); err != nil {
			return err
		}
	}
	var targets []string
	if *dids != "" {
		targets = strings.Split(*dids, ",")
	} else {
		for _, did := range sortedKeys(sum.Repos) {
			st := sum.Repos[did]
			if st.Rev == "" || (st.Active != nil && !*st.Active) {
				continue
			}
			targets = append(targets, did)
		}
	}
	if len(targets) == 0 {
		return fmt.Errorf("no repos to check")
	}

	fail := &failures{}
	rc := repoChecker{pds: strings.TrimRight(*pds, "/"), res: resolver{plc: strings.TrimRight(*plc, "/")}, fail: fail}
	for _, did := range targets {
		rc.check(context.Background(), did, sum.Repos[did])
	}
	log.Printf("repo: checked %d repos on %s, %d failures", len(targets), *pds, fail.count())
	if n := fail.count(); n > 0 {
		return fmt.Errorf("%d repo check failures", n)
	}
	return nil
}

type repoChecker struct {
	pds  string
	res  resolver
	fail *failures
}

func (rc repoChecker) check(ctx context.Context, did string, st *repoState) {
	bad := func(format string, args ...any) { rc.fail.add(did+": "+format, args...) }

	carBytes, _, err := getBytes(ctx, xrpcURL(rc.pds, "com.atproto.sync.getRepo", map[string]string{"did": did}))
	if err != nil {
		bad("getRepo: %v", err)
		return
	}
	if err := verifyBlockHashes(carBytes); err != nil {
		bad("getRepo CAR: %v", err)
	}
	commit, r, err := repo.LoadRepoFromCAR(ctx, bytes.NewReader(carBytes))
	if err != nil {
		bad("load repo CAR: %v", err)
		return
	}
	commitCID, err := carRoot(carBytes)
	if err != nil {
		bad("CAR root: %v", err)
		return
	}
	ident, err := rc.res.lookup(ctx, did)
	if err != nil {
		bad("resolve: %v", err)
	} else if pub, err := ident.PublicKey(); err != nil {
		bad("signing key: %v", err)
	} else if err := commit.VerifySignature(pub); err != nil {
		bad("repo commit signature: %v", err)
	}
	if err := r.MST.Verify(); err != nil {
		bad("MST structure: %v", err)
	}
	records := map[string]cid.Cid{}
	if err := r.MST.WriteToMap(records); err != nil {
		bad("walk MST: %v", err)
		return
	}
	// rebuild from the record set alone: a valid but non-canonical tree
	// would still load, so the root must match the canonical one
	canon, err := mst.LoadTreeFromMap(records)
	if err != nil {
		bad("rebuild MST: %v", err)
	} else if root, err := canon.RootCID(); err != nil {
		bad("rebuild MST root: %v", err)
	} else if root.String() != commit.Data.String() {
		bad("commit data %s is not the canonical MST root %s", commit.Data, root)
	}
	for path, c := range records {
		blk, err := r.RecordStore.Get(ctx, c)
		if err != nil {
			bad("record %s block %s missing from CAR", path, c)
			continue
		}
		if len(blk.RawData()) == 0 {
			bad("record %s is empty", path)
		}
	}

	if st != nil {
		if st.Rev != commit.Rev {
			bad("repo rev %s, firehose last showed %s", commit.Rev, st.Rev)
		}
		if st.Commit != commitCID.String() {
			bad("repo commit %s, firehose last showed %s", commitCID, st.Commit)
		}
		if st.Data != commit.Data.String() {
			bad("repo data %s, firehose last showed %s", commit.Data, st.Data)
		}
		if st.Complete {
			for path, c := range records {
				if st.Records[path] != c.String() {
					bad("record %s is %s in the repo, %q from the firehose", path, c, st.Records[path])
				}
			}
			for path := range st.Records {
				if _, ok := records[path]; !ok {
					bad("record %s from the firehose is not in the repo", path)
				}
			}
		}
	}

	var latest struct {
		CID string `json:"cid"`
		Rev string `json:"rev"`
	}
	if err := getJSONFrom(ctx, xrpcURL(rc.pds, "com.atproto.sync.getLatestCommit", map[string]string{"did": did}), &latest); err != nil {
		bad("getLatestCommit: %v", err)
	} else if latest.CID != commitCID.String() || latest.Rev != commit.Rev {
		bad("getLatestCommit %s/%s, repo is %s/%s", latest.CID, latest.Rev, commitCID, commit.Rev)
	}

	var status struct {
		Active bool   `json:"active"`
		Rev    string `json:"rev"`
	}
	if err := getJSONFrom(ctx, xrpcURL(rc.pds, "com.atproto.sync.getRepoStatus", map[string]string{"did": did}), &status); err != nil {
		bad("getRepoStatus: %v", err)
	} else {
		if !status.Active {
			bad("getRepoStatus says inactive")
		}
		if status.Rev != "" && status.Rev != commit.Rev {
			bad("getRepoStatus rev %s, repo is %s", status.Rev, commit.Rev)
		}
	}

	rc.checkListings(ctx, did, records)
	rc.checkRecordProofs(ctx, did, commitCID, records)
	rc.checkBlobs(ctx, did)
}

// listRecords and repo.getRecord must agree with the exported repo
func (rc repoChecker) checkListings(ctx context.Context, did string, records map[string]cid.Cid) {
	bad := func(format string, args ...any) { rc.fail.add(did+": "+format, args...) }
	var desc struct {
		Collections []string `json:"collections"`
	}
	if err := getJSONFrom(ctx, xrpcURL(rc.pds, "com.atproto.repo.describeRepo", map[string]string{"repo": did}), &desc); err != nil {
		bad("describeRepo: %v", err)
		return
	}
	wantCollections := map[string]bool{}
	for path := range records {
		col, _, _ := strings.Cut(path, "/")
		wantCollections[col] = true
	}
	got := map[string]bool{}
	for _, c := range desc.Collections {
		got[c] = true
		if !wantCollections[c] {
			bad("describeRepo lists %s, which has no records", c)
		}
	}
	listed := map[string]string{}
	for col := range wantCollections {
		if !got[col] {
			bad("describeRepo omits %s", col)
		}
		cursor := ""
		for page := 0; page < 1000; page++ {
			var out struct {
				Cursor  *string `json:"cursor"`
				Records []struct {
					URI string `json:"uri"`
					CID string `json:"cid"`
				} `json:"records"`
			}
			u := xrpcURL(rc.pds, "com.atproto.repo.listRecords", map[string]string{"repo": did, "collection": col, "limit": "7", "cursor": cursor})
			if err := getJSONFrom(ctx, u, &out); err != nil {
				bad("listRecords %s: %v", col, err)
				break
			}
			for _, rec := range out.Records {
				prefix := "at://" + did + "/"
				if !strings.HasPrefix(rec.URI, prefix) {
					bad("listRecords uri %s", rec.URI)
					continue
				}
				path := strings.TrimPrefix(rec.URI, prefix)
				if _, dup := listed[path]; dup {
					bad("listRecords returned %s twice", path)
				}
				listed[path] = rec.CID
			}
			if out.Cursor == nil || *out.Cursor == "" || len(out.Records) == 0 {
				break
			}
			cursor = *out.Cursor
		}
	}
	for path, c := range records {
		if listed[path] != c.String() {
			bad("listRecords has %s as %q, repo has %s", path, listed[path], c)
		}
	}
	for path := range listed {
		if _, ok := records[path]; !ok {
			bad("listRecords has %s, which is not in the repo", path)
		}
	}
	for _, path := range sortedKeys(listed) {
		col, rkey, _ := strings.Cut(path, "/")
		var out struct {
			URI string `json:"uri"`
			CID string `json:"cid"`
		}
		u := xrpcURL(rc.pds, "com.atproto.repo.getRecord", map[string]string{"repo": did, "collection": col, "rkey": rkey})
		if err := getJSONFrom(ctx, u, &out); err != nil {
			bad("getRecord %s: %v", path, err)
		} else if out.CID != records[path].String() {
			bad("getRecord %s cid %s, repo has %s", path, out.CID, records[path])
		}
	}
}

// sync.getRecord returns a commit plus the MST path proving the record
func (rc repoChecker) checkRecordProofs(ctx context.Context, did string, commitCID cid.Cid, records map[string]cid.Cid) {
	bad := func(format string, args ...any) { rc.fail.add(did+": "+format, args...) }
	for _, path := range sortedKeys(records) {
		col, rkey, _ := strings.Cut(path, "/")
		b, _, err := getBytes(ctx, xrpcURL(rc.pds, "com.atproto.sync.getRecord", map[string]string{"did": did, "collection": col, "rkey": rkey}))
		if err != nil {
			bad("sync.getRecord %s: %v", path, err)
			continue
		}
		if err := verifyBlockHashes(b); err != nil {
			bad("sync.getRecord %s CAR: %v", path, err)
			continue
		}
		bs, root, err := loadBlocks(b)
		if err != nil {
			bad("sync.getRecord %s: %v", path, err)
			continue
		}
		if root != commitCID {
			bad("sync.getRecord %s proves commit %s, latest is %s", path, root, commitCID)
		}
		blk, err := bs.Get(ctx, root)
		if err != nil {
			bad("sync.getRecord %s: commit block missing", path)
			continue
		}
		var commit repo.Commit
		if err := commit.UnmarshalCBOR(bytes.NewReader(blk.RawData())); err != nil {
			bad("sync.getRecord %s: commit: %v", path, err)
			continue
		}
		tree, err := mst.LoadTreeFromStore(ctx, bs, commit.Data)
		if err != nil {
			bad("sync.getRecord %s: proof tree: %v", path, err)
			continue
		}
		got, err := tree.Get([]byte(path))
		if err != nil || got == nil {
			bad("sync.getRecord %s: proof does not reach the record (%v)", path, err)
			continue
		}
		if *got != records[path] {
			bad("sync.getRecord %s proves %s, repo has %s", path, got, records[path])
		}
		if _, err := bs.Get(ctx, *got); err != nil {
			bad("sync.getRecord %s: record block missing", path)
		}
	}
}

// every listed blob must come back with bytes that hash to its CID
func (rc repoChecker) checkBlobs(ctx context.Context, did string) {
	bad := func(format string, args ...any) { rc.fail.add(did+": "+format, args...) }
	var out struct {
		CIDs []string `json:"cids"`
	}
	if err := getJSONFrom(ctx, xrpcURL(rc.pds, "com.atproto.sync.listBlobs", map[string]string{"did": did, "limit": "1000"}), &out); err != nil {
		bad("listBlobs: %v", err)
		return
	}
	for _, s := range out.CIDs {
		want, err := cid.Decode(s)
		if err != nil {
			bad("listBlobs cid %q: %v", s, err)
			continue
		}
		b, _, err := getBytes(ctx, xrpcURL(rc.pds, "com.atproto.sync.getBlob", map[string]string{"did": did, "cid": s}))
		if err != nil {
			bad("getBlob %s: %v", s, err)
			continue
		}
		got, err := want.Prefix().Sum(b)
		if err != nil || !got.Equals(want) {
			bad("getBlob %s returned bytes hashing to %s", s, got)
		}
	}
}

func getJSONFrom(ctx context.Context, u string, v any) error {
	b, _, err := getBytes(ctx, u)
	if err != nil {
		return err
	}
	return json.Unmarshal(b, v)
}

func carRoot(b []byte) (cid.Cid, error) {
	cr, err := car.NewCarReader(bytes.NewReader(b))
	if err != nil {
		return cid.Undef, err
	}
	if len(cr.Header.Roots) != 1 {
		return cid.Undef, fmt.Errorf("CAR has %d roots", len(cr.Header.Roots))
	}
	return cr.Header.Roots[0], nil
}

func loadBlocks(b []byte) (*repo.TinyBlockstore, cid.Cid, error) {
	cr, err := car.NewCarReader(bytes.NewReader(b))
	if err != nil {
		return nil, cid.Undef, err
	}
	if len(cr.Header.Roots) != 1 {
		return nil, cid.Undef, fmt.Errorf("CAR has %d roots", len(cr.Header.Roots))
	}
	bs := repo.NewTinyBlockstore()
	for {
		blk, err := cr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, cid.Undef, err
		}
		bs.Put(context.Background(), blk)
	}
	return bs, cr.Header.Roots[0], nil
}

// verifyBlockHashes checks that a CAR is version 1 with one root, that every
// block's bytes hash to its CID, that CIDs are the blessed CIDv1 sha2-256
// kind, and that no block repeats.
func verifyBlockHashes(b []byte) error {
	cr, err := car.NewCarReader(bytes.NewReader(b))
	if err != nil {
		return err
	}
	if cr.Header.Version != 1 {
		return fmt.Errorf("CAR version %d", cr.Header.Version)
	}
	if len(cr.Header.Roots) != 1 {
		return fmt.Errorf("CAR has %d roots", len(cr.Header.Roots))
	}
	seen := map[string]bool{}
	for {
		blk, err := cr.Next()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		c := blk.Cid()
		p := c.Prefix()
		if p.Version != 1 || p.MhType != multihash.SHA2_256 || p.MhLength != 32 {
			return fmt.Errorf("block %s is not a CIDv1 sha2-256", c)
		}
		sum, err := p.Sum(blk.RawData())
		if err != nil {
			return err
		}
		if !sum.Equals(c) {
			return fmt.Errorf("block %s hashes to %s", c, sum)
		}
		if seen[c.KeyString()] {
			return fmt.Errorf("block %s appears twice", c)
		}
		seen[c.KeyString()] = true
	}
}