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

zat.dev/zds

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

0
0
547 lines · 15.0 KB Raw History
package main

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"
	"sync"
	"time"

	comatproto "github.com/bluesky-social/indigo/api/atproto"
	"github.com/bluesky-social/indigo/atproto/repo"
	"github.com/bluesky-social/indigo/atproto/repo/mst"
	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/bluesky-social/indigo/events"
	"github.com/bluesky-social/indigo/events/schedulers/sequential"
	"github.com/gorilla/websocket"
	"github.com/ipfs/go-cid"
)

// protocol limits from the subscribeRepos lexicon and the reference relay
const (
	maxBlocksBytes   = 2_000_000
	maxCommitOps     = 200
	futureRevAllowed = 5 * time.Minute
)

type repoState struct {
	Rev    string `json:"rev"`
	Commit string `json:"commit"`
	Data   string `json:"data"`
	// Records is the repo contents rebuilt from #commit ops. It is only
	// tracked while Complete: the stream showed the repo from its first
	// commit and no #sync reset it since.
	Records  map[string]string `json:"records,omitempty"`
	Complete bool              `json:"complete"`
	Commits  int               `json:"commits"`
	Syncs    int               `json:"syncs"`
	Active   *bool             `json:"active,omitempty"`
	Status   string            `json:"status,omitempty"`
	Handle   string            `json:"handle,omitempty"`
}

type summary struct {
	Source   string                `json:"source"`
	Events   int                   `json:"events"`
	FirstSeq int64                 `json:"firstSeq"`
	LastSeq  int64                 `json:"lastSeq"`
	Kinds    map[string]int        `json:"kinds"`
	Repos    map[string]*repoState `json:"repos"`
	Failures []string              `json:"failures"`
}

type firehoseChecker struct {
	res  resolver
	fail *failures
	mu   sync.Mutex
	sum  summary
	last time.Time
	log  *bufio.Writer
}

func runFirehose(args []string) error {
	fs := flag.NewFlagSet("firehose", flag.ExitOnError)
	host := fs.String("host", "ws://127.0.0.1:2583", "websocket base URL of the PDS or relay")
	plc := fs.String("plc", "http://127.0.0.1:2582", "PLC directory used to resolve signing keys")
	cursor := fs.Int64("cursor", -1, "cursor to start at; -1 starts live with no cursor")
	idle := fs.Duration("idle", 3*time.Second, "stop after this long without an event (once -wait-for exists)")
	waitFor := fs.String("wait-for", "", "do not stop for idleness until this file exists")
	maxDur := fs.Duration("max", 5*time.Minute, "give up after this long")
	minEvents := fs.Int("min-events", 1, "fail if fewer events than this arrived")
	out := fs.String("out", "", "write the state summary JSON here")
	eventsOut := fs.String("events", "", "append one JSON line per event here, for diagnosis")
	fs.Parse(args)

	fc := &firehoseChecker{
		res:  resolver{plc: strings.TrimRight(*plc, "/")},
		fail: &failures{},
		sum: summary{
			Source: *host,
			Kinds:  map[string]int{},
			Repos:  map[string]*repoState{},
		},
		last: time.Now(),
	}
	if *eventsOut != "" {
		f, err := os.Create(*eventsOut)
		if err != nil {
			return err
		}
		defer f.Close()
		fc.log = bufio.NewWriter(f)
		defer fc.log.Flush()
	}

	u := strings.TrimRight(*host, "/") + "/xrpc/com.atproto.sync.subscribeRepos"
	if *cursor >= 0 {
		u += fmt.Sprintf("?cursor=%d", *cursor)
	}
	con, _, err := websocket.DefaultDialer.Dial(u, nil)
	if err != nil {
		return fmt.Errorf("dial %s: %w", u, err)
	}
	ready := os.Getenv("INTEROP_FIREHOSE_READY")
	if ready != "" {
		os.WriteFile(ready, []byte("ok\n"), 0o644)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	started := time.Now()
	go func() {
		t := time.NewTicker(200 * time.Millisecond)
		defer t.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-t.C:
			}
			if time.Since(started) > *maxDur {
				fc.fail.add("firehose %s: still running after %s", *host, *maxDur)
				cancel()
				con.Close()
				return
			}
			if *waitFor != "" {
				if _, err := os.Stat(*waitFor); err != nil {
					continue
				}
			}
			fc.mu.Lock()
			quiet := time.Since(fc.last)
			fc.mu.Unlock()
			if quiet > *idle {
				cancel()
				con.Close()
				return
			}
		}
	}()

	rsc := &events.RepoStreamCallbacks{
		RepoCommit:   fc.onCommit,
		RepoSync:     fc.onSync,
		RepoIdentity: fc.onIdentity,
		RepoAccount:  fc.onAccount,
		RepoInfo: func(evt *comatproto.SyncSubscribeRepos_Info) error {
			fc.mu.Lock()
			defer fc.mu.Unlock()
			fc.touch("info")
			msg := ""
			if evt.Message != nil {
				msg = *evt.Message
			}
			fc.fail.add("firehose sent #info %s: %s", evt.Name, msg)
			return nil
		},
		Error: func(evt *events.ErrorFrame) error {
			fc.fail.add("firehose error frame %s: %s", evt.Error, evt.Message)
			return nil
		},
	}
	sched := sequential.NewScheduler("interop-check", rsc.EventHandler)
	err = events.HandleRepoStream(ctx, con, sched, nil)
	if err != nil && ctx.Err() == nil && !errors.Is(err, context.Canceled) {
		fc.fail.add("firehose stream ended: %v", err)
	}

	fc.mu.Lock()
	defer fc.mu.Unlock()
	if fc.sum.Events < *minEvents {
		fc.fail.add("firehose %s: %d events, expected at least %d", *host, fc.sum.Events, *minEvents)
	}
	fc.sum.Failures = fc.fail.list()
	if *out != "" {
		if err := writeJSONFile(*out, fc.sum); err != nil {
			return err
		}
	}
	log.Printf("firehose %s: %d events (%v), %d repos, %d failures", *host, fc.sum.Events, fc.sum.Kinds, len(fc.sum.Repos), fc.fail.count())
	if n := fc.fail.count(); n > 0 {
		return fmt.Errorf("%d firehose check failures", n)
	}
	return nil
}

// touch records an event; callers hold fc.mu
func (fc *firehoseChecker) touch(kind string) {
	fc.last = time.Now()
	fc.sum.Events++
	fc.sum.Kinds[kind]++
}

// seq checks ordering; callers hold fc.mu
func (fc *firehoseChecker) seq(kind string, seq int64, did string) {
	if fc.sum.FirstSeq == 0 {
		fc.sum.FirstSeq = seq
	}
	if seq <= fc.sum.LastSeq {
		fc.fail.add("seq=%d %s %s: seq not after previous %d", seq, kind, did, fc.sum.LastSeq)
	}
	fc.sum.LastSeq = seq
}

func (fc *firehoseChecker) state(did string) *repoState {
	st, ok := fc.sum.Repos[did]
	if !ok {
		st = &repoState{}
		fc.sum.Repos[did] = st
	}
	return st
}

func (fc *firehoseChecker) record(v map[string]any) {
	if fc.log == nil {
		return
	}
	b, _ := json.Marshal(v)
	fc.log.Write(append(b, '\n'))
}

func (fc *firehoseChecker) verifySig(ctx context.Context, commit *repo.Commit) error {
	ident, err := fc.res.lookup(ctx, commit.DID)
	if err != nil {
		return fmt.Errorf("resolve: %w", err)
	}
	pub, err := ident.PublicKey()
	if err == nil {
		if err = commit.VerifySignature(pub); err == nil {
			return nil
		}
	}
	// replays can predate a key rotation; accept a key the DID published before
	keys, kerr := fc.res.historicKeys(ctx, commit.DID)
	if kerr != nil {
		return err
	}
	for _, k := range keys {
		if commit.VerifySignature(k) == nil {
			return nil
		}
	}
	return err
}

func (fc *firehoseChecker) onCommit(evt *comatproto.SyncSubscribeRepos_Commit) error {
	ctx := context.Background()
	fc.mu.Lock()
	defer fc.mu.Unlock()
	fc.touch("commit")
	fc.seq("commit", evt.Seq, evt.Repo)
	where := fmt.Sprintf("seq=%d commit %s rev=%s", evt.Seq, evt.Repo, evt.Rev)
	bad := func(format string, args ...any) { fc.fail.add(where+": "+format, args...) }

	ops := make([]map[string]any, 0, len(evt.Ops))
	for _, op := range evt.Ops {
		if op == nil {
			continue
		}
		o := map[string]any{"action": op.Action, "path": op.Path}
		if op.Cid != nil {
			o["cid"] = cid.Cid(*op.Cid).String()
		}
		if op.Prev != nil {
			o["prev"] = cid.Cid(*op.Prev).String()
		}
		ops = append(ops, o)
	}
	entry := map[string]any{"seq": evt.Seq, "type": "commit", "did": evt.Repo, "rev": evt.Rev, "ops": ops, "blocks": len(evt.Blocks)}
	if evt.Since != nil {
		entry["since"] = *evt.Since
	}
	if evt.PrevData != nil {
		entry["prevData"] = cid.Cid(*evt.PrevData).String()
	}
	defer fc.record(entry)

	if !validDID(evt.Repo) {
		bad("invalid DID")
		return nil
	}
	if len(evt.Blocks) == 0 {
		bad("no blocks")
		return nil
	}
	if len(evt.Blocks) > maxBlocksBytes {
		bad("blocks are %d bytes, over the %d limit", len(evt.Blocks), maxBlocksBytes)
	}
	if len(evt.Ops) > maxCommitOps {
		bad("%d ops, over the %d limit", len(evt.Ops), maxCommitOps)
	}
	if evt.TooBig {
		bad("deprecated tooBig set")
	}
	if evt.Rebase {
		bad("deprecated rebase set")
	}
	if _, err := syntax.ParseDatetime(evt.Time); err != nil {
		bad("time %q: %v", evt.Time, err)
	}
	for _, op := range evt.Ops {
		if op == nil {
			bad("nil op")
			return nil
		}
		// sync 1.1: updates and deletes carry the previous record CID so
		// consumers can invert the commit; creates must not
		switch op.Action {
		case "create":
			if op.Cid == nil || op.Prev != nil {
				bad("create %s needs cid and no prev", op.Path)
			}
		case "update":
			if op.Cid == nil || op.Prev == nil {
				bad("update %s needs cid and prev", op.Path)
			}
		case "delete":
			if op.Cid != nil || op.Prev == nil {
				bad("delete %s needs prev and no cid", op.Path)
			}
		default:
			bad("unknown op action %q", op.Action)
		}
	}

	commit, commitCID, err := repo.LoadCommitFromCAR(ctx, bytes.NewReader(evt.Blocks))
	if err != nil {
		bad("load commit: %v", err)
		return nil
	}
	if commitCID.String() != cid.Cid(evt.Commit).String() {
		bad("event commit %s is not the CAR root %s", cid.Cid(evt.Commit), commitCID)
	}
	if commit.DID != evt.Repo {
		bad("commit DID %s", commit.DID)
	}
	if commit.Rev != evt.Rev {
		bad("commit rev %s", commit.Rev)
	}
	if rev, err := syntax.ParseTID(commit.Rev); err != nil {
		bad("rev: %v", err)
	} else if rev.Time().After(time.Now().Add(futureRevAllowed)) {
		bad("rev is in the future (%s)", rev.Time())
	}
	if err := fc.verifySig(ctx, commit); err != nil {
		bad("signature: %v", err)
	}
	if err := verifyBlockHashes(evt.Blocks); err != nil {
		bad("blocks: %v", err)
	}

	st := fc.state(evt.Repo)
	first := st.Rev == ""
	if !first {
		if evt.PrevData == nil {
			bad("missing prevData")
		} else if cid.Cid(*evt.PrevData).String() != st.Data {
			bad("prevData %s is not the previous commit's data %s", cid.Cid(*evt.PrevData), st.Data)
		}
		if evt.Since == nil {
			bad("missing since")
		} else if *evt.Since != st.Rev {
			bad("since %s is not the previous rev %s", *evt.Since, st.Rev)
		}
		if evt.Rev <= st.Rev {
			bad("rev does not advance past %s", st.Rev)
		}
	} else if evt.Since == nil && evt.PrevData == nil {
		// the repo's first commit: everything after it can be modelled
		st.Complete = true
		st.Records = map[string]string{}
	}
	if evt.PrevData != nil {
		if _, err := repo.VerifyCommitMessage(ctx, evt); err != nil {
			bad("MST inversion: %v", err)
		}
	}

	if st.Complete {
		for _, op := range evt.Ops {
			cur, exists := st.Records[op.Path]
			switch op.Action {
			case "create":
				if exists {
					bad("create %s, which already exists", op.Path)
				}
				st.Records[op.Path] = cid.Cid(*op.Cid).String()
			case "update", "delete":
				if !exists {
					bad("%s %s, which does not exist", op.Action, op.Path)
				} else if op.Prev != nil && cid.Cid(*op.Prev).String() != cur {
					bad("%s %s prev %s, current is %s", op.Action, op.Path, cid.Cid(*op.Prev), cur)
				}
				if op.Action == "update" && op.Cid != nil {
					st.Records[op.Path] = cid.Cid(*op.Cid).String()
				} else {
					delete(st.Records, op.Path)
				}
			}
		}
		root, err := rootFromRecords(st.Records)
		if err != nil {
			bad("rebuild MST: %v", err)
		} else if root != commit.Data.String() {
			bad("commit data %s, but the records so far build %s", commit.Data, root)
		}
	}

	st.Rev = commit.Rev
	st.Commit = commitCID.String()
	st.Data = commit.Data.String()
	st.Commits++
	return nil
}

func (fc *firehoseChecker) onSync(evt *comatproto.SyncSubscribeRepos_Sync) error {
	ctx := context.Background()
	fc.mu.Lock()
	defer fc.mu.Unlock()
	fc.touch("sync")
	fc.seq("sync", evt.Seq, evt.Did)
	where := fmt.Sprintf("seq=%d sync %s rev=%s", evt.Seq, evt.Did, evt.Rev)
	bad := func(format string, args ...any) { fc.fail.add(where+": "+format, args...) }
	defer fc.record(map[string]any{"seq": evt.Seq, "type": "sync", "did": evt.Did, "rev": evt.Rev, "blocks": len(evt.Blocks)})

	if len(evt.Blocks) > maxBlocksBytes {
		bad("blocks are %d bytes", len(evt.Blocks))
	}
	if _, err := syntax.ParseDatetime(evt.Time); err != nil {
		bad("time %q: %v", evt.Time, err)
	}
	commit, commitCID, err := repo.LoadCommitFromCAR(ctx, bytes.NewReader(evt.Blocks))
	if err != nil {
		bad("load commit: %v", err)
		return nil
	}
	if commit.DID != evt.Did || commit.Rev != evt.Rev {
		bad("commit is %s rev %s", commit.DID, commit.Rev)
	}
	if err := fc.verifySig(ctx, commit); err != nil {
		bad("signature: %v", err)
	}
	st := fc.state(evt.Did)
	if st.Rev != "" && commit.Rev < st.Rev {
		bad("rev goes back from %s", st.Rev)
	}
	st.Rev = commit.Rev
	st.Commit = commitCID.String()
	st.Data = commit.Data.String()
	st.Complete = false
	st.Records = nil
	st.Syncs++
	return nil
}

func (fc *firehoseChecker) onIdentity(evt *comatproto.SyncSubscribeRepos_Identity) error {
	fc.mu.Lock()
	defer fc.mu.Unlock()
	fc.touch("identity")
	fc.seq("identity", evt.Seq, evt.Did)
	entry := map[string]any{"seq": evt.Seq, "type": "identity", "did": evt.Did}
	defer fc.record(entry)
	where := fmt.Sprintf("seq=%d identity %s", evt.Seq, evt.Did)
	if !validDID(evt.Did) {
		fc.fail.add("%s: invalid DID", where)
		return nil
	}
	if _, err := syntax.ParseDatetime(evt.Time); err != nil {
		fc.fail.add("%s: time %q: %v", where, evt.Time, err)
	}
	st := fc.state(evt.Did)
	if evt.Handle != nil {
		entry["handle"] = *evt.Handle
		if _, err := syntax.ParseHandle(*evt.Handle); err != nil {
			fc.fail.add("%s: handle %q: %v", where, *evt.Handle, err)
		}
		st.Handle = *evt.Handle
	}
	return nil
}

var accountStatuses = map[string]bool{
	"takendown": true, "suspended": true, "deleted": true, "deactivated": true,
	"desynchronized": true, "throttled": true,
}

func (fc *firehoseChecker) onAccount(evt *comatproto.SyncSubscribeRepos_Account) error {
	fc.mu.Lock()
	defer fc.mu.Unlock()
	fc.touch("account")
	fc.seq("account", evt.Seq, evt.Did)
	entry := map[string]any{"seq": evt.Seq, "type": "account", "did": evt.Did, "active": evt.Active}
	defer fc.record(entry)
	where := fmt.Sprintf("seq=%d account %s", evt.Seq, evt.Did)
	if !validDID(evt.Did) {
		fc.fail.add("%s: invalid DID", where)
	}
	if _, err := syntax.ParseDatetime(evt.Time); err != nil {
		fc.fail.add("%s: time %q: %v", where, evt.Time, err)
	}
	st := fc.state(evt.Did)
	active := evt.Active
	st.Active = &active
	st.Status = ""
	if evt.Status != nil {
		entry["status"] = *evt.Status
		st.Status = *evt.Status
		if !accountStatuses[*evt.Status] {
			fc.fail.add("%s: unknown status %q", where, *evt.Status)
		}
	}
	if !active && evt.Status == nil {
		fc.fail.add("%s: inactive without a status", where)
	}
	if active && evt.Status != nil {
		fc.fail.add("%s: active with status %q", where, *evt.Status)
	}
	return nil
}

// rootFromRecords builds the canonical MST for a path->CID map and returns its root.
func rootFromRecords(records map[string]string) (string, error) {
	m := make(map[string]cid.Cid, len(records))
	for k, v := range records {
		c, err := cid.Decode(v)
		if err != nil {
			return "", err
		}
		m[k] = c
	}
	tree, err := mst.LoadTreeFromMap(m)
	if err != nil {
		return "", err
	}
	root, err := tree.RootCID()
	if err != nil {
		return "", err
	}
	return root.String(), nil
}