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

zat.dev/zds

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

0
0
234 lines · 6.0 KB Raw History
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/did-method-plc/go-didplc"
)

// plcDirectory is an in-memory PLC directory that validates every submitted
// operation the way plc.directory does (signature against the previous
// rotation keys, DID derived from the genesis op, CID chain) and serves DID
// documents computed from the latest valid op. A PDS under test writes
// genesis and update ops to it; the checkers and relays resolve through it.
type plcDirectory struct {
	mu   sync.Mutex
	logs map[string][]didplc.LogEntry
	// extra documents served verbatim, for DIDs hosted outside the harness
	seeded map[string]json.RawMessage
}

func runPLC(args []string) error {
	fs := flag.NewFlagSet("plc", flag.ExitOnError)
	listen := fs.String("listen", "127.0.0.1:2582", "address to serve on")
	seed := fs.String("seed", "", "optional JSON file of {did: document} served without validation")
	fs.Parse(args)

	dir := &plcDirectory{logs: map[string][]didplc.LogEntry{}, seeded: map[string]json.RawMessage{}}
	if *seed != "" {
		b, err := readFile(*seed)
		if err != nil {
			return err
		}
		if err := json.Unmarshal(b, &dir.seeded); err != nil {
			return fmt.Errorf("seed file: %w", err)
		}
	}
	log.Printf("plc directory listening on %s", *listen)
	return http.ListenAndServe(*listen, dir)
}

func (d *plcDirectory) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path, err := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/"))
	if err != nil {
		httpError(w, 400, "bad path")
		return
	}
	if path == "_health" {
		writeJSON(w, 200, map[string]string{"status": "ok"})
		return
	}
	did, rest, _ := strings.Cut(path, "/")
	if !strings.HasPrefix(did, "did:plc:") {
		httpError(w, 404, "not found")
		return
	}
	switch r.Method {
	case http.MethodPost:
		if rest != "" {
			httpError(w, 404, "not found")
			return
		}
		d.submit(w, r, did)
	case http.MethodGet:
		d.get(w, did, rest)
	default:
		httpError(w, 405, "method not allowed")
	}
}

func (d *plcDirectory) submit(w http.ResponseWriter, r *http.Request, did string) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		httpError(w, 400, "read body")
		return
	}
	var op didplc.OpEnum
	if err := json.Unmarshal(body, &op); err != nil {
		httpError(w, 400, "invalid operation: "+err.Error())
		return
	}
	inner := op.AsOperation()
	if inner == nil {
		httpError(w, 400, "invalid operation type")
		return
	}
	if !inner.IsSigned() {
		httpError(w, 400, "operation is not signed")
		return
	}
	entry := didplc.LogEntry{
		DID:       did,
		Operation: op,
		CID:       inner.CID().String(),
		CreatedAt: syntax.DatetimeNow().String(),
	}
	if err := entry.Validate(); err != nil {
		httpError(w, 400, err.Error())
		return
	}

	d.mu.Lock()
	defer d.mu.Unlock()
	prev := d.logs[did]
	if len(prev) == 0 && !inner.IsGenesis() {
		httpError(w, 404, "DID not registered")
		return
	}
	if len(prev) > 0 {
		if inner.IsGenesis() {
			httpError(w, 409, "DID already registered")
			return
		}
		// forks (nullification) are out of scope: an op must extend the head
		if inner.PrevCIDStr() != prev[len(prev)-1].CID {
			httpError(w, 409, "operation prev is not the current head")
			return
		}
		if prev[len(prev)-1].Operation.Tombstone != nil {
			httpError(w, 410, "DID is tombstoned")
			return
		}
	}
	candidate := append(append([]didplc.LogEntry{}, prev...), entry)
	if err := didplc.VerifyOpLog(candidate); err != nil {
		httpError(w, 400, "operation rejected: "+err.Error())
		return
	}
	d.logs[did] = candidate
	log.Printf("plc accepted %s op for %s (%d in log)", opType(op), did, len(candidate))
	w.WriteHeader(200)
}

func (d *plcDirectory) get(w http.ResponseWriter, did, rest string) {
	d.mu.Lock()
	entries := append([]didplc.LogEntry{}, d.logs[did]...)
	seeded, isSeeded := d.seeded[did]
	d.mu.Unlock()

	if len(entries) == 0 {
		if isSeeded && rest == "" {
			w.Header().Set("content-type", "application/did+ld+json")
			w.WriteHeader(200)
			w.Write(seeded)
			return
		}
		httpError(w, 404, "DID not registered: "+did)
		return
	}
	last := entries[len(entries)-1]
	switch rest {
	case "":
		if last.Operation.Tombstone != nil {
			httpError(w, 410, "DID not available: "+did)
			return
		}
		doc, err := last.Operation.AsOperation().Doc(did)
		if err != nil {
			httpError(w, 500, err.Error())
			return
		}
		out := map[string]any{
			"@context": []string{
				"https://www.w3.org/ns/did/v1",
				"https://w3id.org/security/multikey/v1",
				"https://w3id.org/security/suites/secp256k1-2019/v1",
			},
			"id":                 doc.ID,
			"alsoKnownAs":        doc.AlsoKnownAs,
			"verificationMethod": doc.VerificationMethod,
			"service":            doc.Service,
		}
		writeJSON(w, 200, out)
	case "log":
		ops := make([]didplc.OpEnum, 0, len(entries))
		for _, e := range entries {
			ops = append(ops, e.Operation)
		}
		writeJSON(w, 200, ops)
	case "log/audit":
		writeJSON(w, 200, entries)
	case "log/last":
		writeJSON(w, 200, &last.Operation)
	case "data":
		if last.Operation.Regular == nil {
			httpError(w, 410, "DID not available: "+did)
			return
		}
		op := *last.Operation.Regular
		writeJSON(w, 200, map[string]any{
			"did":                 did,
			"rotationKeys":        op.RotationKeys,
			"verificationMethods": op.VerificationMethods,
			"alsoKnownAs":         op.AlsoKnownAs,
			"services":            op.Services,
		})
	default:
		httpError(w, 404, "not found")
	}
}

func opType(op didplc.OpEnum) string {
	switch {
	case op.Regular != nil && op.Regular.IsGenesis():
		return "genesis"
	case op.Regular != nil:
		return "update"
	case op.Tombstone != nil:
		return "tombstone"
	default:
		return "legacy"
	}
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("content-type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(v)
}

func httpError(w http.ResponseWriter, status int, msg string) {
	writeJSON(w, status, map[string]string{"message": msg})
}

var plcClient = &http.Client{Timeout: 10 * time.Second}