1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// mesh_test.go builds a local mesh of ActivityPub instances that talk to each
// other entirely inside one process: no sockets, no subprocesses, no files.
//
// # Why this exists
//
// Testing instance-to-instance behaviour normally means provisioning hosts:
// two domains, two TLS certificates, two deployments, and a slow, flaky
// feedback loop for what are actually pure questions about protocol
// behaviour ("does a Follow get Accepted?", "is a cross-origin activity
// rejected?"). The mesh answers those questions in milliseconds.
//
// # How it works
//
// A Server's outbound requests go through Config.Transport. meshTransport
// implements http.RoundTripper by looking up req.URL.Host in a table of
// in-process http.ServeMux instances and replaying the request into the
// matching one with httptest.NewRecorder. Delivery therefore becomes a
// function call, and an unknown host becomes a connection error — which is a
// free and accurate model of an unreachable instance.
//
// # What stays real
//
// Everything above the transport. Requests are signed and verified with real
// RSA keys, bodies are really digested, WebFinger really resolves, and the
// FEP-fe34 owner and origin checks really run. Only the socket is absent.
// Because no socket is dialled, the SSRF-safe dialer of security.md §4 is
// bypassed rather than weakened: safeSocketControl is never reached, and
// production builds — which never set Config.Transport — keep it in full.
//
// Origins need no special treatment: a node configured with Domain "a.test"
// produces exactly the ids a deployed instance would
// (https://a.test/users/alice), so no port or scheme artifacts leak into
// stored state.
package activitypub

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"testing"
	"time"
)

// ---------------------------------------------------------------------------
// In-memory Store
// ---------------------------------------------------------------------------

// memStore is a Store backed by a map, so mesh tests touch no filesystem.
// Writes are atomic by construction: the map entry is replaced under a lock.
type memStore struct {
	mu    sync.Mutex
	files map[string][]byte
}

func newMemStore() *memStore {
	return &memStore{files: map[string][]byte{}}
}

func (m *memStore) ReadFile(name string) ([]byte, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	data, ok := m.files[name]
	if !ok {
		// Must satisfy errors.Is(err, os.ErrNotExist): New and
		// loadOrGenerateKey use it to tell "no state yet" from a real error.
		return nil, &os.PathError{Op: "open", Path: name, Err: os.ErrNotExist}
	}
	return append([]byte(nil), data...), nil
}

func (m *memStore) WriteFile(name string, data []byte, _ os.FileMode) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.files[name] = append([]byte(nil), data...)
	return nil
}

// has reports whether a state file has been written yet.
func (m *memStore) has(name string) bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	_, ok := m.files[name]
	return ok
}

// ---------------------------------------------------------------------------
// Mesh transport
// ---------------------------------------------------------------------------

// mesh is a set of in-process instances addressed by hostname.
type mesh struct {
	mu    sync.Mutex
	hosts map[string]http.Handler

	// wg tracks background goroutines of every node, so a test can wait for
	// the whole mesh to fall quiet. A cascade cannot be missed: a delivery
	// runs the receiver's handler synchronously inside the sender's call, so
	// the receiver has registered its own work before the sender's goroutine
	// completes.
	wg sync.WaitGroup

	// registry scopes actor registration to this mesh, so that two meshes in
	// one test binary may both use "a.test" without clobbering each other.
	registry *Registry
}

func newMesh() *mesh {
	return &mesh{
		hosts:    map[string]http.Handler{},
		registry: NewRegistry(),
	}
}

func (m *mesh) addHost(host string, h http.Handler) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.hosts[host] = h
}

func (m *mesh) lookup(host string) (http.Handler, bool) {
	m.mu.Lock()
	defer m.mu.Unlock()
	h, ok := m.hosts[host]
	return h, ok
}

// settle waits for all background work in the mesh to finish.
func (m *mesh) settle() { m.wg.Wait() }

// meshTransport routes an outbound request to the in-process instance that
// serves req.URL.Host.
type meshTransport struct{ mesh *mesh }

func (t *meshTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	handler, ok := t.mesh.lookup(req.URL.Host)
	if !ok {
		// Models an unreachable instance (NXDOMAIN / connection refused).
		return nil, fmt.Errorf("mesh: no instance serving host %q", req.URL.Host)
	}

	var body io.Reader = http.NoBody
	if req.Body != nil {
		data, err := io.ReadAll(req.Body)
		req.Body.Close()
		if err != nil {
			return nil, fmt.Errorf("mesh: read request body: %w", err)
		}
		body = strings.NewReader(string(data))
	}

	// RequestURI carries path and query, so the (request-target) line the
	// receiver reconstructs matches the one the sender signed.
	in := httptest.NewRequest(req.Method, req.URL.RequestURI(), body)

	for k, vs := range req.Header {
		for _, v := range vs {
			in.Header.Add(k, v)
		}
	}

	// signRequest sets a literal Host header, but net/http promotes Host out
	// of the header map into Request.Host on the server side, and that is
	// where verifyHTTPSignature reads it from. Move it across by hand so the
	// signed "host" line and the verified one agree.
	if h := req.Header.Get("Host"); h != "" {
		in.Host = h
	} else {
		in.Host = req.URL.Host
	}
	in.Header.Del("Host")

	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, in)

	resp := rec.Result()
	resp.Request = req
	return resp, nil
}

// ---------------------------------------------------------------------------
// Nodes
// ---------------------------------------------------------------------------

// node is one instance in the mesh: a domain, a mux, and its actors.
type node struct {
	mesh   *mesh
	domain string
	mux    *http.ServeMux
	actors map[string]*Server
	stores map[string]*memStore
}

// newNode creates an instance serving domain and joins it to the mesh.
func newNode(m *mesh, domain string) *node {
	n := &node{
		mesh:   m,
		domain: domain,
		mux:    http.NewServeMux(),
		actors: map[string]*Server{},
		stores: map[string]*memStore{},
	}
	m.addHost(domain, n.mux)
	return n
}

// addActor creates an actor on this instance. The first actor added also
// registers the domain-wide routes (WebFinger, shared inbox).
func (n *node) addActor(t *testing.T, name string) *Server {
	t.Helper()

	// Seed the store with a pooled key rather than passing Config.PrivateKey:
	// the server then takes the normal loadOrGenerateKey path, so key
	// persistence is exercised and a restart against this store finds the
	// same key — while still skipping a 100ms RSA generation.
	store := newMemStore()
	seedKey(t, store, testKey(t))

	srv, err := New(Config{
		Domain:    n.domain,
		ActorName: name,
		ActorType: "Person",
		Summary:   name + " on " + n.domain,
		Store:     store,
		Transport: &meshTransport{mesh: n.mesh},
		Registry:  n.mesh.registry,
		WaitGroup: &n.mesh.wg,
	})
	if err != nil {
		t.Fatalf("create actor %s@%s: %v", name, n.domain, err)
	}

	first := len(n.actors) == 0
	srv.RegisterActor(n.mux)
	if first {
		srv.RegisterDomain(n.mux)
	}

	n.actors[name] = srv
	n.stores[name] = store
	return srv
}

// ---------------------------------------------------------------------------
// Test keys
// ---------------------------------------------------------------------------

// RSA-2048 generation costs roughly 100ms, which would dominate the runtime of
// a mesh with a handful of actors. The keys below are generated once per test
// binary and handed out in rotation.
//
// They must be distinct: a mesh where every actor shared one key would verify
// every signature regardless of who signed it, and the signature tests would
// prove nothing.
var (
	keyPoolOnce sync.Once
	keyPool     []*rsa.PrivateKey
	keyPoolIdx  int
	keyPoolMu   sync.Mutex
)

const keyPoolSize = 8

// seedKey writes key as key.pem into store, in the same PKCS#1 PEM encoding
// loadOrGenerateKey writes and expects.
func seedKey(t *testing.T, store Store, key *rsa.PrivateKey) {
	t.Helper()
	pemData := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	})
	if err := store.WriteFile("key.pem", pemData, 0o600); err != nil {
		t.Fatalf("seed key: %v", err)
	}
}

func testKey(t *testing.T) *rsa.PrivateKey {
	t.Helper()
	keyPoolOnce.Do(func() {
		keyPool = make([]*rsa.PrivateKey, keyPoolSize)
		var wg sync.WaitGroup
		for i := range keyPool {
			wg.Add(1)
			go func(i int) {
				defer wg.Done()
				k, err := rsa.GenerateKey(rand.Reader, 2048)
				if err != nil {
					panic(err)
				}
				keyPool[i] = k
			}(i)
		}
		wg.Wait()
	})

	keyPoolMu.Lock()
	defer keyPoolMu.Unlock()
	if keyPoolIdx >= len(keyPool) {
		// More actors than pooled keys: generate a fresh one rather than
		// silently reusing a key and weakening the test.
		k, err := rsa.GenerateKey(rand.Reader, 2048)
		if err != nil {
			t.Fatalf("generate key: %v", err)
		}
		return k
	}
	k := keyPool[keyPoolIdx]
	keyPoolIdx++
	return k
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

// follow makes `from` follow `to`, exactly as an application would: resolve
// the target's inbox, then post a Follow activity to it.
func follow(t *testing.T, from *Server, toActorURL string) {
	t.Helper()
	inbox, err := from.ResolveInbox(toActorURL)
	if err != nil {
		t.Fatalf("resolve inbox of %s: %v", toActorURL, err)
	}
	activity := map[string]any{
		"@context": "https://www.w3.org/ns/activitystreams",
		"id":       fmt.Sprintf("%s#follows/%d", from.ActorURL(), time.Now().UnixNano()),
		"type":     "Follow",
		"actor":    from.ActorURL(),
		"object":   toActorURL,
	}
	if err := from.PostToInbox(inbox, activity); err != nil {
		t.Fatalf("post Follow to %s: %v", inbox, err)
	}
}

func (s *Server) followerList() []string {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return append([]string(nil), s.followers...)
}

func (s *Server) followingList() []string {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return append([]string(nil), s.following...)
}

func (s *Server) inboxSnapshot() []map[string]any {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return append([]map[string]any(nil), s.inbox...)
}

func containsURL(list []string, want string) bool {
	for _, v := range list {
		if v == want {
			return true
		}
	}
	return false
}